perf(dashboard): play clip previews from R2, not from the render box

Each result card streamed its clip from /videos, which is served by the
same single-worker API process that is running the renders, while the
same clip was already archived to R2 (free egress, edge-served). The
durable URL was in the browser the whole time and was only used as an
error fallback.

It becomes the playback source, but only while R2 holds exactly the file
the server considers current: a server-side edit rewrites the clip and the
re-archive behind it is fire-and-forget, so preferring the durable copy
blindly would show the clip from BEFORE the edit. /api/history therefore
returns the archived filename, and the card compares it against its own
serverVideoFile.

The map is chased after each edit and again once the job completes, since
a job is marked completed before _archive_managed_job finishes uploading
and the first read otherwise lands empty and never retries. The effect
that reads it is keyed on the clip count instead of the results object, so
it no longer re-reads the history on every status poll. The durable copy
is never adopted under a player the user already started, because swapping
src restarts playback.

Display only: currentVideoUrl still drives the download button and every
server operation (all of which pass input_filename, never a URL), so no
edit can be routed to the wrong file by this.
This commit is contained in:
juancarlos.cavero 2026-08-22 19:52:17 +02:00
parent 22d4d1889e
commit e0fa3fd591
3 changed files with 146 additions and 21 deletions

View file

@ -285,6 +285,12 @@ async def history(request: Request):
"title": v.title, "title": v.title,
"created_at": v.created_at.isoformat() if v.created_at else None, "created_at": v.created_at.isoformat() if v.created_at else None,
"size_bytes": v.size_bytes, "size_bytes": v.size_bytes,
# The basename of the archived object. The preview player compares it
# against the clip's current server file: after an edit the local file
# is already the new one while the R2 re-archive is still in flight
# (_archive_clip_edit_bg is fire-and-forget), and playing the durable
# copy then would show the clip from BEFORE the edit.
"filename": (v.r2_key or "").rsplit("/", 1)[-1],
"view_url": storage.presigned_get(v.r2_key, expires=3600), "view_url": storage.presigned_get(v.r2_key, expires=3600),
"download_url": storage.presigned_get(v.r2_key, expires=3600, download_name=safe_name), "download_url": storage.presigned_get(v.r2_key, expires=3600, download_name=safe_name),
}) })

View file

@ -283,7 +283,10 @@ function App() {
// --- Project persistence (paid mode) --- // --- Project persistence (paid mode) ---
// Debounced sync of each clip's browser-only edit state (Remotion layers + // Debounced sync of each clip's browser-only edit state (Remotion layers +
// current server file) to the backend, so a reopened project resumes intact. // current server file) to the backend, so a reopened project resumes intact.
const clipStateSync = useRef({ jobId: null, pending: {}, timer: null }); const clipStateSync = useRef({ jobId: null, pending: {}, files: {}, timer: null });
// Read by in-flight async chases to notice that the user moved on to another job.
const jobIdRef = useRef(jobId);
useEffect(() => { jobIdRef.current = jobId; }, [jobId]);
const flushClipState = () => { const flushClipState = () => {
const s = clipStateSync.current; const s = clipStateSync.current;
@ -303,11 +306,51 @@ function App() {
}).catch(() => {}); }).catch(() => {});
}; };
// One /api/history read, reduced to this job's clips.
const fetchDurableMap = async () => {
const d = await apiJson('/api/history');
const map = {};
for (const v of (d.videos || [])) {
if (v.job_id === jobId && v.clip_index != null) map[v.clip_index] = { url: v.view_url, filename: v.filename };
}
return map;
};
// A server-side edit rewrites the clip's file while the R2 re-archive behind it
// is still in flight (_archive_clip_edit_bg is fire-and-forget), so the durable
// map goes stale and the card falls back to streaming from the API. Re-read the
// map on a backoff until the archived name matches the clip's new file, then it
// can play from R2 again. Gives up quietly: staying on /videos is correct, just
// slower, and is exactly what happens for self-hosted users all the time.
const chaseDurableFile = async (index, expectedFile) => {
const forJob = jobId;
for (const delay of [2500, 6000, 15000, 30000]) {
await new Promise((r) => setTimeout(r, delay));
if (jobIdRef.current !== forJob) return;
let map;
try { map = await fetchDurableMap(); } catch { return; }
// A new job started mid-chase: this map describes the old one, so dropping
// it here keeps it from overwriting the new job's URLs.
if (jobIdRef.current !== forJob) return;
setDurableClips(map);
if (map[index]?.filename === expectedFile) return;
}
};
const handleClipStateChange = (index, state) => { const handleClipStateChange = (index, state) => {
if (!isManaged || !jobId) return; if (!isManaged || !jobId) return;
const s = clipStateSync.current; const s = clipStateSync.current;
if (s.jobId !== jobId) { s.pending = {}; s.jobId = jobId; } if (s.jobId !== jobId) { s.pending = {}; s.files = {}; s.jobId = jobId; }
s.pending[index] = state; s.pending[index] = state;
// Cards report on mount too, so only an actual change of server file means an
// edit just landed. The first report per clip is the mount, never a chase.
const files = s.files || (s.files = {});
const file = state?.serverVideoFile;
if (file && files[index] !== file) {
const isMount = files[index] === undefined;
files[index] = file;
if (!isMount) chaseDurableFile(index, file);
}
if (s.timer) clearTimeout(s.timer); if (s.timer) clearTimeout(s.timer);
s.timer = setTimeout(flushClipState, 2000); s.timer = setTimeout(flushClipState, 2000);
}; };
@ -528,23 +571,47 @@ function App() {
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [uploadPostKey, isManaged]); }, [uploadPostKey, isManaged]);
// For managed users, fetch the durable R2 URLs of the current job's clips so the // For managed users, fetch the durable R2 URLs of the current job's clips. The
// preview can fall back to them when the local files have been cleaned up. // preview player prefers them (free egress, edge-served, and not competing with
// the renders for the API process), and falls back to /videos when the local
// file is newer than the archived one or the signed link fails.
// Kept fresh by chaseDurableFile after each edit and by the completion chase
// below; until either lands, the card just streams from /videos.
useEffect(() => { useEffect(() => {
if (!isManaged || !jobId || !(results?.clips?.length)) { setDurableClips({}); return; } if (!isManaged || !jobId || !(results?.clips?.length)) { setDurableClips({}); return; }
let cancelled = false; let cancelled = false;
apiJson('/api/history') fetchDurableMap()
.then((d) => { .then((map) => { if (!cancelled) setDurableClips(map); })
if (cancelled) return;
const map = {};
for (const v of (d.videos || [])) {
if (v.job_id === jobId && v.clip_index != null) map[v.clip_index] = v.view_url;
}
setDurableClips(map);
})
.catch(() => {}); .catch(() => {});
return () => { cancelled = true; }; return () => { cancelled = true; };
}, [isManaged, jobId, results]); // Keyed on the clip COUNT, not on results: the status poll hands back a new
// results object every couple of seconds while the job runs, and this used to
// re-read the history on every one of them.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isManaged, jobId, results?.clips?.length]);
// A job is marked complete BEFORE _archive_managed_job has finished uploading
// (app.py:878), so the read above can land while R2 still has nothing for it and
// every card would stream from the API for the rest of the session. Chase until
// all clips have a durable copy.
useEffect(() => {
const count = results?.clips?.length || 0;
if (!isManaged || !jobId || status !== 'complete' || !count) return;
let cancelled = false;
(async () => {
for (const delay of [0, 3000, 8000, 20000, 40000]) {
if (delay) await new Promise((r) => setTimeout(r, delay));
if (cancelled) return;
let map;
try { map = await fetchDurableMap(); } catch { return; }
if (cancelled) return;
setDurableClips(map);
if (Object.keys(map).length >= count) return;
}
})();
return () => { cancelled = true; };
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isManaged, jobId, status, results?.clips?.length]);
useEffect(() => { useEffect(() => {
let interval; let interval;
@ -1573,7 +1640,7 @@ function App() {
onReframeClip={(index) => setReframingClip(index)} onReframeClip={(index) => setReframingClip(index)}
initialState={projectState?.clips?.find((c) => c.index === i) || null} initialState={projectState?.clips?.find((c) => c.index === i) || null}
onStateChange={handleClipStateChange} onStateChange={handleClipStateChange}
durableUrl={durableClips[i]} durable={durableClips[i]}
uploadPostKey={uploadPostKey} uploadPostKey={uploadPostKey}
uploadUserId={uploadUserId} uploadUserId={uploadUserId}
geminiApiKey={apiKey} geminiApiKey={apiKey}

View file

@ -35,7 +35,7 @@ function formatDuration(clip) {
return `${String(Math.floor(secs / 60)).padStart(2, '0')}:${String(secs % 60).padStart(2, '0')}`; return `${String(Math.floor(secs / 60)).padStart(2, '0')}:${String(secs % 60).padStart(2, '0')}`;
} }
export default function ResultCard({ clip, index, jobId, durableUrl, uploadPostKey, uploadUserId, geminiApiKey, elevenLabsKey, isManaged, onPlay, onPause, onBulkSubtitle, clipCount = 1, bulkProgress, initialState = null, onStateChange, connectedPlatforms = null, onConnectSocials, onEditClip = null, onReframeClip = null }) { export default function ResultCard({ clip, index, jobId, durable, uploadPostKey, uploadUserId, geminiApiKey, elevenLabsKey, isManaged, onPlay, onPause, onBulkSubtitle, clipCount = 1, bulkProgress, initialState = null, onStateChange, connectedPlatforms = null, onConnectSocials, onEditClip = null, onReframeClip = null }) {
const [showModal, setShowModal] = useState(false); const [showModal, setShowModal] = useState(false);
const [showDescModal, setShowDescModal] = useState(false); const [showDescModal, setShowDescModal] = useState(false);
const [showSubtitleModal, setShowSubtitleModal] = useState(false); const [showSubtitleModal, setShowSubtitleModal] = useState(false);
@ -53,6 +53,28 @@ export default function ResultCard({ clip, index, jobId, durableUrl, uploadPostK
}; };
const originalVideoUrl = getApiUrl((clip.video_url || '').replace(/[^/]+$/, stripBurns((clip.video_url || '').split('/').pop()))); const originalVideoUrl = getApiUrl((clip.video_url || '').replace(/[^/]+$/, stripBurns((clip.video_url || '').split('/').pop())));
const [currentVideoUrl, setCurrentVideoUrl] = useState(getApiUrl(clip.video_url)); const [currentVideoUrl, setCurrentVideoUrl] = useState(getApiUrl(clip.video_url));
// Where the <video> element pulls its bytes from. The clips are archived to
// R2 anyway, and R2 egress is free and edge-served, while /videos is served
// by the same single-worker API process that is running the renders. So play
// from R2 when possible.
//
// ONLY when R2 holds exactly the file the server considers current for this
// clip (durable.filename === serverVideoFile). Every server-side edit sends
// input_filename: serverVideoFile and rewrites clip.video_url, but the R2
// re-archive behind it is fire-and-forget, so for a few seconds the durable
// copy is the PRE-edit clip. Preferring it blindly would silently show the
// clip without the subtitles/hook the user just burned.
//
// This is display-only: currentVideoUrl remains the source of truth for the
// download button and for every server operation, so no edit can be routed
// to the wrong file by this.
const [durableSrc, setDurableSrc] = useState(null);
const [durableFailed, setDurableFailed] = useState(false);
// Switching src reloads the element and restarts playback, so the durable copy
// is only ever adopted before the user has touched this player. After an edit
// the chase in App.jsx can land while they are watching the result, and losing
// their position to save a few seconds of buffering is a bad trade.
const [hasPlayed, setHasPlayed] = useState(false);
const downloadClip = async () => { const downloadClip = async () => {
try { try {
@ -81,14 +103,28 @@ export default function ResultCard({ clip, index, jobId, durableUrl, uploadPostK
const [videoErrored, setVideoErrored] = useState(false); const [videoErrored, setVideoErrored] = useState(false);
const [resolution, setResolution] = useState(null); const [resolution, setResolution] = useState(null);
// Adopt the durable copy only while it matches the current server file, and
// pin the first signed URL seen for that file: /api/history mints a fresh
// signature on every call, and swapping src mid-playback restarts the video.
useEffect(() => {
if (durable?.url && durable.filename && durable.filename === serverVideoFile && !hasPlayed) {
setDurableSrc((prev) => prev || durable.url);
} else {
setDurableSrc(null);
}
}, [durable?.url, durable?.filename, serverVideoFile, hasPlayed]);
// If the local video failed and a durable R2 URL is (now) available, use it. // If the local video failed and a durable R2 URL is (now) available, use it.
// Handles the race where the video errors before the durable URL has loaded. // Handles the race where the video errors before the durable URL has loaded.
// Deliberately NOT version-gated: reaching here means the local file is gone
// (retention sweep after a reload), so an older durable copy still beats a
// broken player.
useEffect(() => { useEffect(() => {
if (videoErrored && durableUrl && currentVideoUrl !== durableUrl) { if (videoErrored && durable?.url && currentVideoUrl !== durable.url) {
setCurrentVideoUrl(durableUrl); setCurrentVideoUrl(durable.url);
setVideoErrored(false); setVideoErrored(false);
} }
}, [videoErrored, durableUrl, currentVideoUrl]); }, [videoErrored, durable, currentVideoUrl]);
// When an external refresh changes this clip's server file (e.g. bulk // When an external refresh changes this clip's server file (e.g. bulk
// subtitles applied from another card), adopt it so the card shows the // subtitles applied from another card), adopt it so the card shows the
@ -99,6 +135,8 @@ export default function ResultCard({ clip, index, jobId, durableUrl, uploadPostK
if (serverName && serverName !== serverVideoFile) { if (serverName && serverName !== serverVideoFile) {
setServerVideoFile(serverName); setServerVideoFile(serverName);
setCurrentVideoUrl(serverUrl); setCurrentVideoUrl(serverUrl);
setDurableFailed(false);
setHasPlayed(false);
if (videoRef.current) videoRef.current.load(); if (videoRef.current) videoRef.current.load();
} }
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
@ -651,6 +689,12 @@ export default function ResultCard({ clip, index, jobId, durableUrl, uploadPostK
} }
}; };
// Browser-rendered previews (Remotion) live in a blob: URL that exists only
// in this tab, so they always win over the durable copy.
const playbackUrl = (durableSrc && !durableFailed && !String(currentVideoUrl || '').startsWith('blob:'))
? durableSrc
: currentVideoUrl;
const durationReadout = formatDuration(clip); const durationReadout = formatDuration(clip);
return ( return (
@ -659,7 +703,7 @@ export default function ResultCard({ clip, index, jobId, durableUrl, uploadPostK
<div className="w-full md:w-[236px] bg-black relative shrink-0 aspect-[9/16] md:aspect-auto group/video"> <div className="w-full md:w-[236px] bg-black relative shrink-0 aspect-[9/16] md:aspect-auto group/video">
<video <video
ref={videoRef} ref={videoRef}
src={currentVideoUrl} src={playbackUrl}
controls controls
className="w-full h-full object-contain" className="w-full h-full object-contain"
playsInline playsInline
@ -667,13 +711,21 @@ export default function ResultCard({ clip, index, jobId, durableUrl, uploadPostK
if (e.target.videoWidth) setResolution(`${e.target.videoWidth}×${e.target.videoHeight}`); if (e.target.videoWidth) setResolution(`${e.target.videoWidth}×${e.target.videoHeight}`);
}} }}
onError={() => { onError={() => {
// The durable copy is unreachable (signature expired after an
// hour on an idle tab, object purged) → serve from the API for
// the rest of this card's life.
if (playbackUrl === durableSrc) {
setDurableFailed(true);
return;
}
// Local /videos/ file gone (e.g. cleaned up after a reload) → // Local /videos/ file gone (e.g. cleaned up after a reload) →
// fall back to the durable R2 copy for managed users. If the // fall back to the durable R2 copy for managed users. If the
// durable URL hasn't loaded yet, the effect above retries. // durable URL hasn't loaded yet, the effect above retries.
if (durableUrl && currentVideoUrl !== durableUrl) setCurrentVideoUrl(durableUrl); if (durable?.url && currentVideoUrl !== durable.url) setCurrentVideoUrl(durable.url);
else setVideoErrored(true); else setVideoErrored(true);
}} }}
onPlay={() => { onPlay={() => {
setHasPlayed(true);
const currentTime = videoRef.current ? videoRef.current.currentTime : 0; const currentTime = videoRef.current ? videoRef.current.currentTime : 0;
onPlay && onPlay(clip.start + currentTime); onPlay && onPlay(clip.start + currentTime);
}} }}