Handle damaged originals that kept failing after Retry #8

Merged
khyretos merged 1 commit from fix/damaged-originals into main 2026-11-07 23:19:40 +01:00
Owner

Requested by Kees · project thread

  • Use the video stream's own length (DURATION tag) when the container
    states a longer one, so samples land inside the video.
  • A sample start with no readable video moves earlier instead of
    producing an empty lossless reference (EBML 'End of file').
  • A copy that is short because the original itself is cut off (no
    video packets after the copy's end) is kept with a note.
  • Leave out subtitle streams with an unknown codec; .ts copies are
    Matroska.

Co-Authored-By: Claude Opus 5.5 noreply@anthropic.com
Claude-Session: https://claude.ai/code/session_018FuQsp6G2DpZQdmAMJuPU3

Tests: 182 pass (10 new, some with real ffmpeg on a cut-off file) in a clean checkout off the box.

🤖 Generated with Claude Code

https://claude.ai/code/session_018FuQsp6G2DpZQdmAMJuPU3

<!-- claude-projects-attribution: {"github_login":"Khyretos"} --> _Requested by **Kees** · [project thread](https://claude.ai/code/project/chan_01VRYAfLZkYLvDjKF95nFnnk?thread=cmsg_01VRYAfLZkYLvDjKF95nFnnkDnFLvdtW19casYdoQNx2uu)_ - Use the video stream's own length (DURATION tag) when the container states a longer one, so samples land inside the video. - A sample start with no readable video moves earlier instead of producing an empty lossless reference (EBML 'End of file'). - A copy that is short because the original itself is cut off (no video packets after the copy's end) is kept with a note. - Leave out subtitle streams with an unknown codec; .ts copies are Matroska. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018FuQsp6G2DpZQdmAMJuPU3 Tests: 182 pass (10 new, some with real ffmpeg on a cut-off file) in a clean checkout off the box. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_018FuQsp6G2DpZQdmAMJuPU3
- Use the video stream's own length (DURATION tag) when the container
  states a longer one, so samples land inside the video.
- A sample start with no readable video moves earlier instead of
  producing an empty lossless reference (EBML 'End of file').
- A copy that is short because the original itself is cut off (no
  video packets after the copy's end) is kept with a note.
- Leave out subtitle streams with an unknown codec; .ts copies are
  Matroska.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018FuQsp6G2DpZQdmAMJuPU3
Collaborator

Title

Handle damaged originals that kept failing after Retry


PR Type

Bug fix, Enhancement


Description

  • Use video stream duration to fix samples landing outside video in damaged files.

  • Keep copies of cut-off originals instead of failing them with bad duration errors.

  • Exclude unknown subtitle codecs and force Matroska container for .ts files.

  • Retry logic now moves sample starts earlier when encountering empty references.


Diagram Walkthrough

flowchart LR
  A["Damaged Original"] -->|"Wrong Duration"| B["Use Stream Duration"]
  A -->|"Cut Off"| C["Check Video Packets"]
  C -->|"No More Video"| D["Keep Copy with Note"]
  C -->|"More Video"| E["Retry CPU Decode"]
  A -->|"Bad Subs"| F["Exclude Unknown Codecs"]
  A -->|".ts File"| G["Force Matroska Container"]

File Walkthrough

Relevant files
Enhancement
1 files
rx_media.py
Add stream duration parsing and video packet checking functions
+55/-1   
Bug fix
2 files
rx_search.py
Retry sample cuts when encountering empty lossless references
+19/-4   
rx_worker.py
Pass bad_subs to encoder and handle cut-off original copies
+12/-4   
Tests
2 files
test_damaged_sources.py
Add comprehensive tests for damaged sources and cut-off files
+151/-0 
test_fixes_2026_11_07.py
Update worker fallback tests to include video_packets_after mock
+4/-1     
Documentation
2 files
detail.js
Display reason messages for staged and confirmed file statuses
+1/-0     
CHANGELOG.md
Document fixes for damaged originals and cut-off downloads
+5/-0     

## Title <!-- pr-agent:describe:persistent --> Handle damaged originals that kept failing after Retry ___ ### **PR Type** Bug fix, Enhancement ___ ### **Description** - Use video stream duration to fix samples landing outside video in damaged files. - Keep copies of cut-off originals instead of failing them with bad duration errors. - Exclude unknown subtitle codecs and force Matroska container for .ts files. - Retry logic now moves sample starts earlier when encountering empty references. ___ ### Diagram Walkthrough ```mermaid flowchart LR A["Damaged Original"] -->|"Wrong Duration"| B["Use Stream Duration"] A -->|"Cut Off"| C["Check Video Packets"] C -->|"No More Video"| D["Keep Copy with Note"] C -->|"More Video"| E["Retry CPU Decode"] A -->|"Bad Subs"| F["Exclude Unknown Codecs"] A -->|".ts File"| G["Force Matroska Container"] ``` <details> <summary><h3> File Walkthrough</h3></summary> <table><thead><tr><th></th><th align="left">Relevant files</th></tr></thead><tbody><tr><td><strong>Enhancement</strong></td><td><details><summary>1 files</summary><table> <tr> <td><strong>rx_media.py</strong><dd><code>Add stream duration parsing and video packet checking functions</code></dd></td> <td><a href="https://git.kreative-kompas.com/khyretos/kk-reencoder/src/branch/fix/damaged-originals/app/rx_media.py">+55/-1</a>&nbsp; &nbsp; </td> </tr> </table></details></td></tr><tr><td><strong>Bug fix</strong></td><td><details><summary>2 files</summary><table> <tr> <td><strong>rx_search.py</strong><dd><code>Retry sample cuts when encountering empty lossless references</code></dd></td> <td><a href="https://git.kreative-kompas.com/khyretos/kk-reencoder/src/branch/fix/damaged-originals/app/rx_search.py">+19/-4</a>&nbsp; &nbsp; </td> </tr> <tr> <td><strong>rx_worker.py</strong><dd><code>Pass bad_subs to encoder and handle cut-off original copies</code></dd></td> <td><a href="https://git.kreative-kompas.com/khyretos/kk-reencoder/src/branch/fix/damaged-originals/app/rx_worker.py">+12/-4</a>&nbsp; &nbsp; </td> </tr> </table></details></td></tr><tr><td><strong>Tests</strong></td><td><details><summary>2 files</summary><table> <tr> <td><strong>test_damaged_sources.py</strong><dd><code>Add comprehensive tests for damaged sources and cut-off files</code></dd></td> <td><a href="https://git.kreative-kompas.com/khyretos/kk-reencoder/src/branch/fix/damaged-originals/tests/test_damaged_sources.py">+151/-0</a>&nbsp; </td> </tr> <tr> <td><strong>test_fixes_2026_11_07.py</strong><dd><code>Update worker fallback tests to include video_packets_after mock</code></dd></td> <td><a href="https://git.kreative-kompas.com/khyretos/kk-reencoder/src/branch/fix/damaged-originals/tests/test_fixes_2026_11_07.py">+4/-1</a>&nbsp; &nbsp; &nbsp; </td> </tr> </table></details></td></tr><tr><td><strong>Documentation</strong></td><td><details><summary>2 files</summary><table> <tr> <td><strong>detail.js</strong><dd><code>Display reason messages for staged and confirmed file statuses</code></dd></td> <td><a href="https://git.kreative-kompas.com/khyretos/kk-reencoder/src/branch/fix/damaged-originals/app/static/detail.js">+1/-0</a>&nbsp; &nbsp; &nbsp; </td> </tr> <tr> <td><strong>CHANGELOG.md</strong><dd><code>Document fixes for damaged originals and cut-off downloads</code></dd></td> <td><a href="https://git.kreative-kompas.com/khyretos/kk-reencoder/src/branch/fix/damaged-originals/CHANGELOG.md">+5/-0</a>&nbsp; &nbsp; &nbsp; </td> </tr> </table></details></td></tr></tr></tbody></table> </details> ___
kompas-review left a comment

3 finding(s) as line comments; the review comment lists all of them.

3 finding(s) as line comments; the review comment lists all of them.
@ -14,0 +22,4 @@
if not tag:
return None
try:
h, m, sec = tag.split(":")
Collaborator

Integer overflow in duration parsing · KK-66b658a0de · low

The stream_duration function parses the DURATION tag by splitting on ":" and converting parts to int/float. If the DURATION tag contains an invalid format like "999999999999:999999999999:999999999999", the calculation int(h) * 3600 + int(m) * 60 + float(sec) could result in an extremely large number that exceeds Python's integer limits in other languages or causes unexpected behavior. While Python handles large integers, this could lead to incorrect duration values being used for sample positioning.

Reply not an issue, false positive or won't fix to dismiss it; it is then not reported again.

**Integer overflow in duration parsing** · `KK-66b658a0de` · low The stream_duration function parses the DURATION tag by splitting on ":" and converting parts to int/float. If the DURATION tag contains an invalid format like "999999999999:999999999999:999999999999", the calculation int(h) * 3600 + int(m) * 60 + float(sec) could result in an extremely large number that exceeds Python's integer limits in other languages or causes unexpected behavior. While Python handles large integers, this could lead to incorrect duration values being used for sample positioning. <sub>Reply `not an issue`, `false positive` or `won't fix` to dismiss it; it is then not reported again.</sub> <!-- kk-finding:66b658a0de -->
@ -14,0 +37,4 @@
["nice", "-n", "19", "ionice", "-c", "3", "ffprobe", "-v", "error", "-select_streams", f"v:{video_index}",
"-show_entries", "packet=pts_time", "-of", "csv=p=0", "-read_intervals", f"{max(0.0, t):.3f}%+{span:g}",
path],
capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=120)
Collaborator

Subprocess timeout risk · KK-d4906bdf60 · low

The video_packets_after function calls ffprobe with a hardcoded 120-second timeout. If the file is large or the system is under heavy load, ffprobe may take longer than 120 seconds to complete, causing the subprocess to be killed prematurely. This would return True (assuming more video exists), potentially leading to incorrect duration calculations or unnecessary retries.

Reply not an issue, false positive or won't fix to dismiss it; it is then not reported again.

**Subprocess timeout risk** · `KK-d4906bdf60` · low The video_packets_after function calls ffprobe with a hardcoded 120-second timeout. If the file is large or the system is under heavy load, ffprobe may take longer than 120 seconds to complete, causing the subprocess to be killed prematurely. This would return True (assuming more video exists), potentially leading to incorrect duration calculations or unnecessary retries. <sub>Reply `not an issue`, `false positive` or `won't fix` to dismiss it; it is then not reported again.</sub> <!-- kk-finding:d4906bdf60 -->
@ -0,0 +76,4 @@
with open(cls.cut, "wb") as f:
f.write(data[: len(data) // 2])
@classmethod
Collaborator

Test file cleanup incomplete · KK-9ccee64fa5 · low

The RealFiles test class creates temporary files in setUpClass but only removes them in tearDownClass. If the test suite is interrupted or fails between setUpClass and tearDownClass, the temporary directory and its contents will not be cleaned up, potentially causing disk space issues or leaving orphaned files on the system.

Reply not an issue, false positive or won't fix to dismiss it; it is then not reported again.

**Test file cleanup incomplete** · `KK-9ccee64fa5` · low The RealFiles test class creates temporary files in setUpClass but only removes them in tearDownClass. If the test suite is interrupted or fails between setUpClass and tearDownClass, the temporary directory and its contents will not be cleaned up, potentially causing disk space issues or leaving orphaned files on the system. <sub>Reply `not an issue`, `false positive` or `won't fix` to dismiss it; it is then not reported again.</sub> <!-- kk-finding:9ccee64fa5 -->
Collaborator

PR Reviewer Guide 🔍

📋 Focus areas: 🔴 3 open · ✅ 0 handled. Every push re-checks them; a handled area moves to Resolved findings at the bottom.

🧪 PR contains tests
⚡ Recommended focus areas for review

Subprocess timeout risk

The video_packets_after function calls ffprobe with a hardcoded 120-second timeout. If the file is large or the system is under heavy load, ffprobe may take longer than 120 seconds to complete, causing the subprocess to be killed prematurely. This would return True (assuming more video exists), potentially leading to incorrect duration calculations or unnecessary retries.

capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=120)
Integer overflow in duration parsing

The stream_duration function parses the DURATION tag by splitting on ":" and converting parts to int/float. If the DURATION tag contains an invalid format like "999999999999:999999999999:999999999999", the calculation int(h) * 3600 + int(m) * 60 + float(sec) could result in an extremely large number that exceeds Python's integer limits in other languages or causes unexpected behavior. While Python handles large integers, this could lead to incorrect duration values being used for sample positioning.

    h, m, sec = tag.split(":")
    return int(h) * 3600 + int(m) * 60 + float(sec)
except ValueError:
    return None
Test file cleanup incomplete

The RealFiles test class creates temporary files in setUpClass but only removes them in tearDownClass. If the test suite is interrupted or fails between setUpClass and tearDownClass, the temporary directory and its contents will not be cleaned up, potentially causing disk space issues or leaving orphaned files on the system.

@classmethod
def tearDownClass(cls):
    shutil.rmtree(cls.tmp)

🗂️ Finding ids (reply with the id and not an issue, false positive or won't fix to dismiss one; it is then not reported again):

  • KK-d4906bdf60 app/rx_media.py:40
  • KK-66b658a0de app/rx_media.py:25
  • KK-9ccee64fa5 tests/test_damaged_sources.py:79
## PR Reviewer Guide 🔍 <!-- pr-agent:review:full --> 📋 **Focus areas:** 🔴 3 open · ✅ 0 handled. Every push re-checks them; a handled area moves to *Resolved findings* at the bottom. <table> <tr><td>🧪&nbsp;<strong>PR contains tests</strong></td></tr> <tr><td>⚡&nbsp;<strong>Recommended focus areas for review</strong><br><br> <details><summary><a href='https://git.kreative-kompas.com/khyretos/kk-reencoder/src/branch/fix/damaged-originals/app/rx_media.py#L40-L40'><strong>Subprocess timeout risk</strong></a> The video_packets_after function calls ffprobe with a hardcoded 120-second timeout. If the file is large or the system is under heavy load, ffprobe may take longer than 120 seconds to complete, causing the subprocess to be killed prematurely. This would return True (assuming more video exists), potentially leading to incorrect duration calculations or unnecessary retries. </summary> ```python capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=120) ``` </details> <details><summary><a href='https://git.kreative-kompas.com/khyretos/kk-reencoder/src/branch/fix/damaged-originals/app/rx_media.py#L25-L28'><strong>Integer overflow in duration parsing</strong></a> The stream_duration function parses the DURATION tag by splitting on ":" and converting parts to int/float. If the DURATION tag contains an invalid format like "999999999999:999999999999:999999999999", the calculation int(h) * 3600 + int(m) * 60 + float(sec) could result in an extremely large number that exceeds Python's integer limits in other languages or causes unexpected behavior. While Python handles large integers, this could lead to incorrect duration values being used for sample positioning. </summary> ```python h, m, sec = tag.split(":") return int(h) * 3600 + int(m) * 60 + float(sec) except ValueError: return None ``` </details> <details><summary><a href='https://git.kreative-kompas.com/khyretos/kk-reencoder/src/branch/fix/damaged-originals/tests/test_damaged_sources.py#L79-L81'><strong>Test file cleanup incomplete</strong></a> The RealFiles test class creates temporary files in setUpClass but only removes them in tearDownClass. If the test suite is interrupted or fails between setUpClass and tearDownClass, the temporary directory and its contents will not be cleaned up, potentially causing disk space issues or leaving orphaned files on the system. </summary> ```python @classmethod def tearDownClass(cls): shutil.rmtree(cls.tmp) ``` </details> </td></tr> </table> <hr> 🗂️ **Finding ids** (reply with the id and `not an issue`, `false positive` or `won't fix` to dismiss one; it is then not reported again): - `KK-d4906bdf60` `app/rx_media.py:40` - `KK-66b658a0de` `app/rx_media.py:25` - `KK-9ccee64fa5` `tests/test_damaged_sources.py:79` <!-- pr-agent-review-state:v1 {"findings":[{"body":"**Subprocess timeout risk**\n\nThe video_packets_after function calls ffprobe with a hardcoded 120-second timeout. If the file is large or the system is under heavy load, ffprobe may take longer than 120 seconds to complete, causing the subprocess to be killed prematurely. This would return True (assuming more video exists), potentially leading to incorrect duration calculations or unnecessary retries.","finding_id":"674ace471ff5","first_seen":"2026-11-07T22:17:22.803877Z","last_seen":"2026-11-07T22:17:22.803877Z","last_seen_head_sha":"0bfd88ed2c5db7f92013ce748e2398f605325a27","line_end":40,"line_start":40,"path":"app/rx_media.py","state":"ACTIVE"},{"body":"**Test file cleanup incomplete**\n\nThe RealFiles test class creates temporary files in setUpClass but only removes them in tearDownClass. If the test suite is interrupted or fails between setUpClass and tearDownClass, the temporary directory and its contents will not be cleaned up, potentially causing disk space issues or leaving orphaned files on the system.","finding_id":"95b3be4dd9f9","first_seen":"2026-11-07T22:17:22.803877Z","last_seen":"2026-11-07T22:17:22.803877Z","last_seen_head_sha":"0bfd88ed2c5db7f92013ce748e2398f605325a27","line_end":81,"line_start":79,"path":"tests/test_damaged_sources.py","state":"ACTIVE"},{"body":"**Integer overflow in duration parsing**\n\nThe stream_duration function parses the DURATION tag by splitting on \":\" and converting parts to int/float. If the DURATION tag contains an invalid format like \"999999999999:999999999999:999999999999\", the calculation int(h) * 3600 + int(m) * 60 + float(sec) could result in an extremely large number that exceeds Python's integer limits in other languages or causes unexpected behavior. While Python handles large integers, this could lead to incorrect duration values being used for sample positioning.","finding_id":"e367261ab3dd","first_seen":"2026-11-07T22:17:22.803877Z","last_seen":"2026-11-07T22:17:22.803877Z","last_seen_head_sha":"0bfd88ed2c5db7f92013ce748e2398f605325a27","line_end":28,"line_start":25,"path":"app/rx_media.py","state":"ACTIVE"}],"last_run":{"complete":true,"excluded_files":[],"head_sha":"0bfd88ed2c5db7f92013ce748e2398f605325a27","kind":"full","run_id":"https://git.kreative-kompas.com/khyretos/kk-reencoder/commit/0bfd88ed2c5db7f92013ce748e2398f605325a27"},"schema_version":1} -->
khyretos deleted branch fix/damaged-originals 2026-11-07 23:19:40 +01:00
Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
khyretos/kk-reencoder!8
No description provided.