Claude commited on
Commit
28435e9
·
1 Parent(s): 597ad13

Fix four bugs from the audit: memory, race, leak, scoring order

Browse files

1. /result drops result.body after first delivery (HTTP 410 on re-fetch).
Previously the rendered HTML/zip was retained for the full job TTL
(10 min), so a busy server could OOM. Alts stay alive on the Job
object so the editor's lazy-fetch keeps working.

2. selectFrameButton sets data-image-filename + aria-pressed
synchronously, before the data-URI fetch awaits. So a saveJSON()
right after Load JSON reads the freshly-loaded pick instead of the
previously-rendered one. As a free bonus, added a per-section
pickToken so a slow earlier fetch can't overwrite a faster later
pick when the user double-clicks.

3. previewURL blob now revoked on pagehide. Previously the blob leaked
per session if the user previewed once and then closed the editor.

4. _save_top_candidate_frames runs gamma normalization before scoring
instead of after. A dark-themed slide deck no longer gets outranked
by a transient bright frame (instructor cutaway, fade flash) — the
score reflects post-correction quality, which is what we render.

Files changed (3) hide show
  1. app/main.py +10 -5
  2. app/pipeline/scenes.py +6 -3
  3. app/templates/review.html +21 -6
app/main.py CHANGED
@@ -269,15 +269,20 @@ async def fetch_result(job_id: str) -> Response:
269
  raise HTTPException(422, job.error or "Pipeline error.")
270
  if job.status != "done" or job.result is None:
271
  raise HTTPException(409, "Job not finished.")
 
 
 
 
272
 
273
  headers: dict[str, str] = {}
274
  if job.result.filename:
275
  headers["Content-Disposition"] = f'attachment; filename="{job.result.filename}"'
276
- return Response(
277
- content=job.result.body,
278
- media_type=job.result.media_type,
279
- headers=headers,
280
- )
 
281
 
282
 
283
  _ALT_FILENAME_RE = __import__("re").compile(r"^scene_\d{4}_alt\d+\.(jpg|jpeg|png)$")
 
269
  raise HTTPException(422, job.error or "Pipeline error.")
270
  if job.status != "done" or job.result is None:
271
  raise HTTPException(409, "Job not finished.")
272
+ if not job.result.body:
273
+ # Body was already delivered and freed; alts are still fetchable
274
+ # but the rendered HTML/zip itself is one-shot.
275
+ raise HTTPException(410, "Result already delivered.")
276
 
277
  headers: dict[str, str] = {}
278
  if job.result.filename:
279
  headers["Content-Disposition"] = f'attachment; filename="{job.result.filename}"'
280
+ body = job.result.body
281
+ media = job.result.media_type
282
+ # Free the (potentially MB-scale) HTML/zip body now that it's been
283
+ # delivered — the editor keeps the alts alive via job.alt_image_bytes.
284
+ job.result.body = b""
285
+ return Response(content=body, media_type=media, headers=headers)
286
 
287
 
288
  _ALT_FILENAME_RE = __import__("re").compile(r"^scene_\d{4}_alt\d+\.(jpg|jpeg|png)$")
app/pipeline/scenes.py CHANGED
@@ -114,7 +114,11 @@ def _save_top_candidate_frames(
114
  ok, frame = cap.read()
115
  if not ok or frame is None:
116
  continue
117
- scored.append((_brightness_score(frame), frame))
 
 
 
 
118
  finally:
119
  cap.release()
120
 
@@ -126,10 +130,9 @@ def _save_top_candidate_frames(
126
  saved: list[Path] = []
127
  out_dir.mkdir(parents=True, exist_ok=True)
128
  for i, (_, frame) in enumerate(keep):
129
- normalized = _normalize_brightness(frame)
130
  suffix = "" if i == 0 else f"_alt{i}"
131
  dest = out_dir / f"scene_{scene_index:04d}{suffix}.jpg"
132
- if cv2.imwrite(str(dest), normalized):
133
  saved.append(dest)
134
  return saved
135
 
 
114
  ok, frame = cap.read()
115
  if not ok or frame is None:
116
  continue
117
+ # Normalize first so a dark-themed slide isn't outranked by a
118
+ # transient bright frame (e.g. instructor cutaway, fade flash);
119
+ # we want the score to reflect post-correction visual quality.
120
+ normalized = _normalize_brightness(frame)
121
+ scored.append((_brightness_score(normalized), normalized))
122
  finally:
123
  cap.release()
124
 
 
130
  saved: list[Path] = []
131
  out_dir.mkdir(parents=True, exist_ok=True)
132
  for i, (_, frame) in enumerate(keep):
 
133
  suffix = "" if i == 0 else f"_alt{i}"
134
  dest = out_dir / f"scene_{scene_index:04d}{suffix}.jpg"
135
+ if cv2.imwrite(str(dest), frame):
136
  saved.append(dest)
137
  return saved
138
 
app/templates/review.html CHANGED
@@ -646,18 +646,27 @@
646
  async function selectFrameButton(section, btn) {
647
  const fn = btn.getAttribute('data-frame-filename');
648
  const mainImg = section.querySelector('[data-bind="image"]');
649
- // Optimistic UI: mark pressed immediately so it feels responsive.
 
 
 
 
650
  section.querySelectorAll('.vgm-frame-picker__btn').forEach(
651
  b => b.setAttribute('aria-pressed', b === btn ? 'true' : 'false')
652
  );
 
 
 
 
 
653
  try {
654
  const uri = await ensureDataUriOnButton(btn);
655
- if (mainImg && uri) {
656
- mainImg.src = uri;
657
- mainImg.setAttribute('data-image-filename', fn || '');
658
- }
659
  } catch (err) {
660
- setStatus(err.message || 'Could not load alternate frame.');
 
 
661
  }
662
  }
663
 
@@ -902,6 +911,12 @@
902
  }
903
 
904
  let previewURL = null;
 
 
 
 
 
 
905
  function previewHTML() {
906
  const html = buildFinalHTML();
907
  // Use a Blob URL — opening an empty window and document.write'ing into
 
646
  async function selectFrameButton(section, btn) {
647
  const fn = btn.getAttribute('data-frame-filename');
648
  const mainImg = section.querySelector('[data-bind="image"]');
649
+ // Update the canonical filename + pressed state SYNCHRONOUSLY so a
650
+ // saveJSON() call right after this returns reads the new pick, even
651
+ // if the data URI fetch is still in flight. The visual <img src>
652
+ // catches up async.
653
+ if (mainImg) mainImg.setAttribute('data-image-filename', fn || '');
654
  section.querySelectorAll('.vgm-frame-picker__btn').forEach(
655
  b => b.setAttribute('aria-pressed', b === btn ? 'true' : 'false')
656
  );
657
+ // Token-guard against rapid clicks: only the most recent pick wins
658
+ // when its fetch finally resolves, so an earlier slow fetch can't
659
+ // overwrite a later one's image.
660
+ const token = (section.__pickToken || 0) + 1;
661
+ section.__pickToken = token;
662
  try {
663
  const uri = await ensureDataUriOnButton(btn);
664
+ if (section.__pickToken !== token) return;
665
+ if (mainImg && uri) mainImg.src = uri;
 
 
666
  } catch (err) {
667
+ if (section.__pickToken === token) {
668
+ setStatus(err.message || 'Could not load alternate frame.');
669
+ }
670
  }
671
  }
672
 
 
911
  }
912
 
913
  let previewURL = null;
914
+ window.addEventListener('pagehide', () => {
915
+ if (previewURL) {
916
+ URL.revokeObjectURL(previewURL);
917
+ previewURL = null;
918
+ }
919
+ });
920
  function previewHTML() {
921
  const html = buildFinalHTML();
922
  // Use a Blob URL — opening an empty window and document.write'ing into