From 106ab8b9bbb82273897478865e312cd63ac33b69 Mon Sep 17 00:00:00 2001 From: Nika Siradze Date: Tue, 24 Nov 2026 01:40:48 +0400 Subject: [PATCH 1/2] Pick clips faster on long episodes and cut the Claude startup cost Two things made picking slow on a long episode. A bare claude --print loads every plugin, hook and MCP server the user has configured before it reads the prompt, about 23s on a busy setup against 4s with --tools empty, --strict-mcp-config, --disable-slash-commands and --no-session-persistence. These calls only need text in and text out, so they now use those flags, and fall back to the plain command if an older CLI rejects them. An episode over 45 minutes went to the model in one prompt with a 180s timeout. On a 77 minute episode that call took 138s to 251s, so it often timed out and the fallback read a sampled half of the transcript. Long episodes are now split into windows that are asked at the same time, with a longer timeout per window and the same total number of candidates, ranked together as before. Shorter episodes keep the single prompt. --- backend/services/ai_cli.py | 45 ++++++++++++------ backend/services/claude_suggest.py | 37 +++++++++------ tests/test_ai_fallback.py | 70 +++++++++++++++++++++++++--- tests/test_claude_suggest_helpers.py | 14 +++++- 4 files changed, 129 insertions(+), 37 deletions(-) diff --git a/backend/services/ai_cli.py b/backend/services/ai_cli.py index b112651..837d2d6 100644 --- a/backend/services/ai_cli.py +++ b/backend/services/ai_cli.py @@ -428,6 +428,12 @@ def _format_timeout_label(timeout: int) -> str: return f"{timeout}s" +# A bare `claude --print` loads every plugin, hook and MCP server the user has +# configured before it reads the prompt (about 20s on a busy setup, 4s without). +# These calls only need text in and text out. +CLAUDE_LEAN_FLAGS = ["--tools", "", "--strict-mcp-config", "--disable-slash-commands", "--no-session-persistence"] + + def _run_ai_command( cli_path: str, engine: str, @@ -473,19 +479,32 @@ def _run_ai_command( return result shell = sys.platform == "win32" and cli_path.lower().endswith((".cmd", ".bat")) - cmd = f'"{cli_path}" --print -p -' if shell else [cli_path, "--print", "-p", "-"] - with open(prompt_file, encoding="utf-8") as prompt_fh: - return subprocess.run( - cmd, - stdin=prompt_fh, - capture_output=True, - text=True, - encoding="utf-8", - errors="replace", - cwd=project_dir, - timeout=timeout, - shell=shell, - ) + + def run_claude(cmd): + with open(prompt_file, encoding="utf-8") as prompt_fh: + return subprocess.run( + cmd, + stdin=prompt_fh, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + cwd=project_dir, + timeout=timeout, + shell=shell, + ) + + if shell: + return run_claude(f'"{cli_path}" --print -p -') + result = run_claude([cli_path, "--print", "-p", "-", *CLAUDE_LEAN_FLAGS]) + if result.returncode != 0 and _rejects_flags(result.stderr): + return run_claude([cli_path, "--print", "-p", "-"]) + return result + + +def _rejects_flags(stderr: str) -> bool: + low = (stderr or "").lower() + return any(s in low for s in ("unknown option", "unrecognized option", "unknown argument", "unexpected argument", "invalid option")) def classify_cli_error(detail: str) -> str: diff --git a/backend/services/claude_suggest.py b/backend/services/claude_suggest.py index 75df857..ff5e90c 100644 --- a/backend/services/claude_suggest.py +++ b/backend/services/claude_suggest.py @@ -8,6 +8,7 @@ """ import hashlib +from concurrent.futures import ThreadPoolExecutor import json import math import os @@ -496,6 +497,12 @@ def _split_prompt_for_cache(prompt: str, transcript_text: str) -> tuple[str, str FULL_PROMPT_CHAR_BUDGET = 400000 CANDIDATE_OVERSAMPLE = 2 +# One call that reads a long episode and writes a long answer outlasts its +# timeout on a slow model, and the fallback then reads a sampled transcript. +# Past this length the episode is split and the windows are asked together. +PARALLEL_WINDOW_MIN_MINUTES = 45 +MAX_PARALLEL_WINDOWS = 4 +WINDOW_TIMEOUT = 180 def _build_transcript_text(segments: list[dict]) -> str: @@ -520,14 +527,17 @@ def _segments_duration_seconds(segments: list[dict]) -> float: def _should_bucket_initial_selection(segments: list[dict]) -> bool: """ - Bucket the search only when the transcript text is too big for one prompt. + Bucket the search when the transcript is too big for one prompt, or the + episode is long enough that one call would outlast its timeout. A single prompt lets the model compare moments across the whole episode, - so buckets are the fallback for transcripts past FULL_PROMPT_CHAR_BUDGET. + so shorter episodes keep it. """ if not segments: return False + if _segments_duration_seconds(segments) > PARALLEL_WINDOW_MIN_MINUTES * 60: + return True return len(_build_transcript_text(segments)) > FULL_PROMPT_CHAR_BUDGET @@ -1021,24 +1031,21 @@ def suggest_initial_with_claude( ) if progress_callback: - progress_callback(0, f"Long episode detected: searching {len(buckets)} timeline buckets...") + progress_callback(0, f"Long episode detected: searching {len(buckets)} timeline buckets together...") - aggregated: list[dict] = [] - per_bucket_top_n = max(2, top_n) + per_bucket_top_n = max(2, math.ceil(top_n * CANDIDATE_OVERSAMPLE / len(buckets))) - for idx, bucket in enumerate(buckets): + def search_bucket(item): + idx, bucket = item bucket_label = ( f"bucket {idx + 1}/{len(buckets)} " f"[{int(bucket['start'] // 60)}:{int(bucket['start'] % 60):02d}-" f"{int(bucket['end'] // 60)}:{int(bucket['end'] % 60):02d}]" ) - if progress_callback: - progress_callback(0, f"Searching {bucket_label}...") - - bucket_clips = suggest_with_claude( + return suggest_with_claude( segments=bucket["segments"], top_n=per_bucket_top_n, - exclude_clips=exclude_clips + aggregated, + exclude_clips=exclude_clips, progress_callback=( None if progress_callback is None else lambda pct, msg, bucket_label=bucket_label: progress_callback( @@ -1047,16 +1054,16 @@ def suggest_initial_with_claude( ) ), error_sink=error_sink, - timeout=90, + timeout=WINDOW_TIMEOUT, reaction_times=[ t for t in (reaction_times or []) if bucket["start"] <= t <= bucket["end"] ] or None, bounds=bounds, ) - if not bucket_clips: - continue - aggregated.extend(bucket_clips) + with ThreadPoolExecutor(max_workers=min(MAX_PARALLEL_WINDOWS, len(buckets))) as pool: + found = list(pool.map(search_bucket, enumerate(buckets))) + aggregated: list[dict] = [clip for clips in found if clips for clip in clips] deduped = _dedupe_clips_by_range(aggregated) if len(deduped) >= top_n: diff --git a/tests/test_ai_fallback.py b/tests/test_ai_fallback.py index cba48a5..6f21596 100644 --- a/tests/test_ai_fallback.py +++ b/tests/test_ai_fallback.py @@ -1,6 +1,7 @@ import json import os import subprocess +import threading import sys import tempfile import unittest @@ -208,14 +209,33 @@ def fake_suggest(*, segments, top_n, exclude_clips=None, progress_callback=None, self.assertIsNotNone(clips) self.assertGreaterEqual(len(calls), 4) - self.assertTrue(all(call["timeout"] == 90 for call in calls[:4])) + self.assertTrue(all(call["timeout"] == cs.WINDOW_TIMEOUT for call in calls[:4])) self.assertTrue(all(call["end"] - call["start"] < 2500 for call in calls[:4])) - self.assertGreaterEqual(calls[1]["exclude_len"], 1) + + def test_long_episode_windows_are_asked_at_the_same_time(self): + segments = [ + {"start": float(i * 330), "end": float(i * 330) + 45.0, "speaker": "SPEAKER_00", "text": f"Segment {i}."} + for i in range(17) + ] + in_flight = threading.Barrier(4, timeout=10) + + def fake_suggest(*, segments, top_n, **kw): + in_flight.wait() + first = segments[0]["start"] + return [{ + "title": f"Clip {first}", "start_second": first, "end_second": first + 28.0, + "segments": [{"start": first, "end": first + 28.0}], "duration": 28, "score": 5.0, + }] + + with mock.patch.object(cs, "suggest_with_claude", side_effect=fake_suggest): + clips = cs.suggest_initial_with_claude(segments=segments, top_n=3) + + self.assertEqual(len(clips), 3) def test_a_transcript_that_fits_one_prompt_is_read_whole_and_ranked_down(self): segments = [] for i in range(20): - start = float(i * 330) + start = float(i * 100) segments.append({ "start": start, "end": start + 45.0, @@ -285,9 +305,9 @@ def fake_suggest(*, segments, top_n, **kw): clips = cs.suggest_initial_with_claude(segments=segments, top_n=3) self.assertEqual(len(calls), 5) - self.assertEqual({call["top_n"] for call in calls}, {3}) - self.assertEqual([c["title"] for c in clips], ["Clip 0.0-0", "Clip 0.0-1", "Clip 0.0-2"]) - self.assertEqual([c["score"] for c in clips], [90.0, 89.0, 88.0]) + self.assertEqual({call["top_n"] for call in calls}, {2}) + self.assertEqual([c["title"] for c in clips[:2]], ["Clip 0.0-0", "Clip 0.0-1"]) + self.assertEqual([c["score"] for c in clips], [90.0, 89.0, 10.0]) def test_suggest_with_claude_allows_slack_on_both_ends_of_the_format_bounds(self): segments = [ @@ -575,10 +595,46 @@ def test_get_ai_cli_status_reports_candidates(self): ) args, kwargs = run_mock.call_args - self.assertEqual(args[0], [cli, "--print", "-p", "-"]) + self.assertEqual(args[0], [cli, "--print", "-p", "-", *ai.CLAUDE_LEAN_FLAGS]) self.assertIn("stdin", kwargs) self.assertFalse(kwargs.get("shell")) + def test_claude_falls_back_to_the_plain_command_when_the_cli_rejects_the_lean_flags(self): + with tempfile.TemporaryDirectory() as tmp: + prompt_file = os.path.join(tmp, "prompt.txt") + with open(prompt_file, "w", encoding="utf-8") as fh: + fh.write("find clips") + cli = os.path.join(tmp, "claude") + rejected = subprocess.CompletedProcess(args=[], returncode=1, stdout="", stderr="error: unknown option '--tools'") + accepted = subprocess.CompletedProcess(args=[], returncode=0, stdout="{}", stderr="") + + with mock.patch("services.ai_cli.subprocess.run", side_effect=[rejected, accepted]) as run_mock: + result = ai._run_ai_command( + cli_path=cli, engine="claude", prompt="find clips", + prompt_file=prompt_file, project_dir=tmp, timeout=30, + ) + + self.assertEqual(result.stdout, "{}") + self.assertEqual(run_mock.call_count, 2) + self.assertEqual(run_mock.call_args_list[1].args[0], [cli, "--print", "-p", "-"]) + + def test_claude_keeps_a_real_failure_instead_of_retrying_without_the_lean_flags(self): + with tempfile.TemporaryDirectory() as tmp: + prompt_file = os.path.join(tmp, "prompt.txt") + with open(prompt_file, "w", encoding="utf-8") as fh: + fh.write("find clips") + cli = os.path.join(tmp, "claude") + failed = subprocess.CompletedProcess(args=[], returncode=1, stdout="", stderr="usage limit reached") + + with mock.patch("services.ai_cli.subprocess.run", return_value=failed) as run_mock: + result = ai._run_ai_command( + cli_path=cli, engine="claude", prompt="find clips", + prompt_file=prompt_file, project_dir=tmp, timeout=30, + ) + + self.assertEqual(result.returncode, 1) + self.assertEqual(run_mock.call_count, 1) + def test_codex_exec_uses_current_read_only_args(self): with tempfile.TemporaryDirectory() as tmp: prompt_file = os.path.join(tmp, "prompt.txt") diff --git a/tests/test_claude_suggest_helpers.py b/tests/test_claude_suggest_helpers.py index 729f67a..d0c8a29 100644 --- a/tests/test_claude_suggest_helpers.py +++ b/tests/test_claude_suggest_helpers.py @@ -95,16 +95,26 @@ def test_short_episode_does_not_bucket(self): segments = [{"start": 0, "end": 10, "text": "short"}] self.assertFalse(cs._should_bucket_initial_selection(segments)) - def test_a_three_hour_conversation_that_fits_one_prompt_does_not_bucket(self): + def test_a_three_hour_conversation_is_searched_in_windows_even_when_it_fits_one_prompt(self): segments = [ {"start": i * 5.4, "end": i * 5.4 + 5.0, "text": "a short spoken line here"} for i in range(2000) ] self.assertGreater(segments[-1]["end"], 10000) + self.assertTrue(cs._should_bucket_initial_selection(segments)) + + def test_an_episode_just_under_the_window_length_is_read_whole(self): + minutes = cs.PARALLEL_WINDOW_MIN_MINUTES + segments = [{"start": 0, "end": minutes * 60 - 1, "text": "talk"}] self.assertFalse(cs._should_bucket_initial_selection(segments)) + def test_an_episode_just_over_the_window_length_is_searched_in_windows(self): + minutes = cs.PARALLEL_WINDOW_MIN_MINUTES + segments = [{"start": 0, "end": minutes * 60 + 1, "text": "talk"}] + self.assertTrue(cs._should_bucket_initial_selection(segments)) + def test_many_short_segments_do_not_bucket(self): - segments = [{"start": i, "end": i + 1, "text": "hi"} for i in range(5000)] + segments = [{"start": i * 0.1, "end": i * 0.1 + 0.1, "text": "hi"} for i in range(5000)] self.assertFalse(cs._should_bucket_initial_selection(segments)) def test_text_just_under_the_budget_does_not_bucket(self): From 451135dc8af4adec27b4e563a34d034959dbfe40 Mon Sep 17 00:00:00 2001 From: Nika Siradze Date: Tue, 24 Nov 2026 02:21:17 +0400 Subject: [PATCH 2/2] Keep a failed window from discarding the others, and split the candidate budget exactly A window that raised, for example a stalled cloud request, escaped the thread pool and threw away every other window's picks. The cloud call now reports a timeout as a failed attempt like the CLI and API paths, and a window that fails for any reason returns nothing instead of raising. The per-window ask rounded up and had a floor of two, so a small request split across many windows asked for more than top_n x 2 candidates. The budget is now divided so the windows add up to it. --- backend/services/ai_provider.py | 3 ++ backend/services/claude_suggest.py | 44 +++++++++++++++++------------- tests/test_ai_fallback.py | 26 ++++++++++++++++-- 3 files changed, 51 insertions(+), 22 deletions(-) diff --git a/backend/services/ai_provider.py b/backend/services/ai_provider.py index 24322a0..d65acf5 100644 --- a/backend/services/ai_provider.py +++ b/backend/services/ai_provider.py @@ -203,6 +203,9 @@ def _run_cloud(purpose: str, instruction: str, system: Optional[str], episode_source_hash=episode_source_hash, timeout=timeout, ) + except TimeoutError: + return AIResult(ok=False, provider="cloud", label="podcli Pro", + error=f"podcli Pro timed out ({ai_cli._format_timeout_label(timeout)} limit)") except podcli_cloud.CloudError as exc: return AIResult(ok=False, provider="cloud", label="podcli Pro", error=str(exc)) diff --git a/backend/services/claude_suggest.py b/backend/services/claude_suggest.py index ff5e90c..037f846 100644 --- a/backend/services/claude_suggest.py +++ b/backend/services/claude_suggest.py @@ -1033,7 +1033,9 @@ def suggest_initial_with_claude( if progress_callback: progress_callback(0, f"Long episode detected: searching {len(buckets)} timeline buckets together...") - per_bucket_top_n = max(2, math.ceil(top_n * CANDIDATE_OVERSAMPLE / len(buckets))) + budget = top_n * CANDIDATE_OVERSAMPLE + share, extra = divmod(budget, len(buckets)) + window_top_n = [max(1, share + (1 if i < extra else 0)) for i in range(len(buckets))] def search_bucket(item): idx, bucket = item @@ -1042,24 +1044,28 @@ def search_bucket(item): f"[{int(bucket['start'] // 60)}:{int(bucket['start'] % 60):02d}-" f"{int(bucket['end'] // 60)}:{int(bucket['end'] % 60):02d}]" ) - return suggest_with_claude( - segments=bucket["segments"], - top_n=per_bucket_top_n, - exclude_clips=exclude_clips, - progress_callback=( - None if progress_callback is None - else lambda pct, msg, bucket_label=bucket_label: progress_callback( - pct, - f"{bucket_label}: {msg}" if msg else msg, - ) - ), - error_sink=error_sink, - timeout=WINDOW_TIMEOUT, - reaction_times=[ - t for t in (reaction_times or []) if bucket["start"] <= t <= bucket["end"] - ] or None, - bounds=bounds, - ) + try: + return suggest_with_claude( + segments=bucket["segments"], + top_n=window_top_n[idx], + exclude_clips=exclude_clips, + progress_callback=( + None if progress_callback is None + else lambda pct, msg, bucket_label=bucket_label: progress_callback( + pct, + f"{bucket_label}: {msg}" if msg else msg, + ) + ), + error_sink=error_sink, + timeout=WINDOW_TIMEOUT, + reaction_times=[ + t for t in (reaction_times or []) if bucket["start"] <= t <= bucket["end"] + ] or None, + bounds=bounds, + ) + except Exception as exc: + print(f"Moment search error in {bucket_label}: {exc}", file=sys.stderr, flush=True) + return None with ThreadPoolExecutor(max_workers=min(MAX_PARALLEL_WINDOWS, len(buckets))) as pool: found = list(pool.map(search_bucket, enumerate(buckets))) diff --git a/tests/test_ai_fallback.py b/tests/test_ai_fallback.py index 6f21596..9380201 100644 --- a/tests/test_ai_fallback.py +++ b/tests/test_ai_fallback.py @@ -212,6 +212,26 @@ def fake_suggest(*, segments, top_n, exclude_clips=None, progress_callback=None, self.assertTrue(all(call["timeout"] == cs.WINDOW_TIMEOUT for call in calls[:4])) self.assertTrue(all(call["end"] - call["start"] < 2500 for call in calls[:4])) + def test_one_window_that_raises_does_not_discard_the_others(self): + segments = [ + {"start": float(i * 330), "end": float(i * 330) + 45.0, "speaker": "SPEAKER_00", "text": f"Segment {i}."} + for i in range(17) + ] + + def fake_suggest(*, segments, top_n, **kw): + first = segments[0]["start"] + if first == 0.0: + raise TimeoutError("cloud stalled") + return [{ + "title": f"Clip {first}", "start_second": first, "end_second": first + 28.0, + "segments": [{"start": first, "end": first + 28.0}], "duration": 28, "score": 5.0, + }] + + with mock.patch.object(cs, "suggest_with_claude", side_effect=fake_suggest): + clips = cs.suggest_initial_with_claude(segments=segments, top_n=3) + + self.assertEqual(len(clips), 3) + def test_long_episode_windows_are_asked_at_the_same_time(self): segments = [ {"start": float(i * 330), "end": float(i * 330) + 45.0, "speaker": "SPEAKER_00", "text": f"Segment {i}."} @@ -305,9 +325,9 @@ def fake_suggest(*, segments, top_n, **kw): clips = cs.suggest_initial_with_claude(segments=segments, top_n=3) self.assertEqual(len(calls), 5) - self.assertEqual({call["top_n"] for call in calls}, {2}) - self.assertEqual([c["title"] for c in clips[:2]], ["Clip 0.0-0", "Clip 0.0-1"]) - self.assertEqual([c["score"] for c in clips], [90.0, 89.0, 10.0]) + self.assertEqual(sum(call["top_n"] for call in calls), 3 * cs.CANDIDATE_OVERSAMPLE) + self.assertEqual(len(clips), 3) + self.assertEqual([c["score"] for c in clips[:2]], [90.0, 89.0]) def test_suggest_with_claude_allows_slack_on_both_ends_of_the_format_bounds(self): segments = [