Skip to content

download_manager: validate the .part BEFORE promoting -- a corrupt re-download must not replace an existing valid dest - #2830

Merged
jaylfc merged 1 commit into
devfrom
exec/tsk-xprnf7
Sep 6, 2026
Merged

download_manager: validate the .part BEFORE promoting -- a corrupt re-download must not replace an existing valid dest#2830
jaylfc merged 1 commit into
devfrom
exec/tsk-xprnf7

Conversation

@jaylfc

@jaylfc jaylfc commented Sep 6, 2026

Copy link
Copy Markdown
Owner

CARD TITLE (intent, not commit subject): download_manager: validate the .part BEFORE promoting -- a corrupt re-download must not replace an existing valid dest

Autonomous build of board card tsk-xprnf7.

When a re-download of an already-installed model produced corrupt bytes
(SHA mismatch), _download promoted the .part onto task.dest BEFORE
validation, then deleted task.dest on mismatch -- destroying the
existing valid file. The fix validates the .part first and only
promotes on success. On mismatch the .part alone is removed and
task.dest is left untouched.

_validate_download now takes a path parameter so callers can validate
either the .part stage file or task.dest, reusing the streamed digest
instead of re-reading the file.

The torrent path in _download_with_fallback already validates before
marking complete: torrent.download() verifies SHA internally and
writes directly to task.dest (no promote step), so the
promote-before-validate defect never applied there.

RED (at cut point):
uv run pytest tests/test_download_manager.py::TestDownloadHttp::test_corrupt_redownload_keeps_existing_dest -q
AssertionError: a corrupt re-download must not delete the existing file
assert False

  • where False = exists()

GREEN (after fix):
uv run pytest tests/test_download_manager.py -q
54 passed

Files:
changelog.d/tsk-xprnf7-validate-before-promote.md | 18 ++++++++
tests/test_download_manager.py | 46 ++++++++++++++++++++
tinyagentos/download_manager.py | 51 +++++++++++++----------
3 files changed, 93 insertions(+), 22 deletions(-)

Summary by CodeRabbit

  • Bug Fixes
    • Prevented corrupted re-downloads from replacing an existing valid installation.
    • Downloads are now verified before being finalized, reducing the risk of incomplete or invalid installations.
    • Failed downloads are cleaned up without removing the previously working installation.
  • Tests
    • Added coverage for both failed re-downloads and successful download completion.

When a re-download of an already-installed model produced corrupt bytes
(SHA mismatch), _download promoted the .part onto task.dest BEFORE
validation, then deleted task.dest on mismatch -- destroying the
existing valid file. The fix validates the .part first and only
promotes on success. On mismatch the .part alone is removed and
task.dest is left untouched.

_validate_download now takes a path parameter so callers can validate
either the .part stage file or task.dest, reusing the streamed digest
instead of re-reading the file.

The torrent path in _download_with_fallback already validates before
marking complete: torrent.download() verifies SHA internally and
writes directly to task.dest (no promote step), so the
promote-before-validate defect never applied there.

RED (at cut point):
  uv run pytest tests/test_download_manager.py::TestDownloadHttp::test_corrupt_redownload_keeps_existing_dest -q
  AssertionError: a corrupt re-download must not delete the existing file
  assert False
  +  where False = exists()

GREEN (after fix):
  uv run pytest tests/test_download_manager.py -q
  54 passed
@qodo-code-review

Copy link
Copy Markdown

ⓘ Qodo reviews are paused because your trial has ended. Ask your workspace admin to add credits to resume reviews. Manage billing

@coderabbitai

coderabbitai Bot commented Sep 6, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Team

Run ID: 233fddd2-fce2-45c3-9b6e-f69880f1712a

📥 Commits

Reviewing files that changed from the base of the PR and between 9cbb425 and 3bdcc87.

📒 Files selected for processing (3)
  • changelog.d/tsk-xprnf7-validate-before-promote.md
  • tests/test_download_manager.py
  • tinyagentos/download_manager.py

Included review availability: Your plan provides up to 4 included reviews per hour; 3 remain after this review.


📝 Walkthrough

Walkthrough

The download manager validates HTTP downloads against their .part files before promotion. Invalid staged files are removed without changing existing destinations. Tests cover failed re-downloads, successful promotion, and stage-file cleanup.

Changes

Download integrity

Layer / File(s) Summary
Validation path contract
tinyagentos/download_manager.py
_validate_download accepts an optional path for existence, size, and SHA-256 checks. Torrent validation passes task.dest explicitly.
HTTP staging, promotion, and coverage
tinyagentos/download_manager.py, tests/test_download_manager.py, changelog.d/tsk-xprnf7-validate-before-promote.md
HTTP downloads validate .part before replacing task.dest. Validation failures remove only the stage file. Tests cover corrupt re-downloads and successful promotion. The changelog records the behavior.

Estimated code review effort: 2 (Simple) | ~10 minutes

Merge Risk: ⚪ Minimal · up to 3bdcc

Corrupt HTTP re-downloads now leave an existing valid destination intact, while valid downloads still promote successfully and clean up staging files. No current merge-blocking risk remains.

Sequence Diagram(s)

sequenceDiagram
  participant _download
  participant _validate_download
  participant Filesystem
  _download->>_validate_download: Validate .part file
  _validate_download->>Filesystem: Check size and SHA-256
  Filesystem-->>_validate_download: Return validation result
  _validate_download-->>_download: Return success or SHA256 mismatch
  _download->>Filesystem: Replace task.dest after success
Loading
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 71.43% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 7 functions across 2 files. (1 skipped: 1… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically describes the main change: validating the .part file before promotion so a corrupt re-download does not replace an existing valid destination.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

Docstring coverage is 71.43% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 7 functions across 2 files. (1 skipped: 1 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch exec/tsk-xprnf7

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@gitar-bot

gitar-bot Bot commented Sep 6, 2026

Copy link
Copy Markdown

Important

You are using the Gitar free plan. Upgrade to unlock code review, CI analysis, auto-apply, custom automations, and more.

Gitar

@kilo-code-bot

kilo-code-bot Bot commented Sep 6, 2026

Copy link
Copy Markdown

Kilo Code Review could not run — your account is out of credits.

Add credits or switch to a free model to enable reviews on this change.

# must never be promoted. Remove only the stage file;
# task.dest may hold a previously-verified model from an
# earlier install and is left untouched.
part.unlink(missing_ok=True)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: part.unlink(missing_ok=True) after validation failure can raise non-FileNotFoundError exceptions (e.g., PermissionError), which would be caught by the outer except Exception handler and mask the actual validation error. The user would see the unlink error instead of "SHA256 mismatch".


Reply with @kilocode-bot fix it to have Kilo Code address this issue.

@@ -340,13 +347,12 @@ async def _download(self, task: DownloadTask, expected_sha256: str | None = None
body is on disk, so a failure can never leave a corrupt weight sitting
at the canonical path where every later "is this model installed?"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: await self._validate_download(task, task.dest) is redundant since path defaults to task.dest. Could be simplified to await self._validate_download(task).


Reply with @kilocode-bot fix it to have Kilo Code address this issue.

@kilo-code-bot

kilo-code-bot Bot commented Sep 6, 2026

Copy link
Copy Markdown

Code Review Summary

Status: 2 Issues Found | Recommendation: Address before merge

Overview

Severity Count
CRITICAL 0
WARNING 1
SUGGESTION 1
Issue Details (click to expand)

WARNING

File Line Issue
tinyagentos/download_manager.py 373 part.unlink(missing_ok=True) after validation failure can raise non-FileNotFoundError exceptions (e.g., PermissionError), masking the actual validation error

SUGGESTION

File Line Issue
tinyagentos/download_manager.py 348 await self._validate_download(task, task.dest) is redundant since path defaults to task.dest
Files Reviewed (3 files)
  • tinyagentos/download_manager.py - 2 issues
  • tests/test_download_manager.py - reviewed
  • changelog.d/tsk-xprnf7-validate-before-promote.md - reviewed

Fix these issues in Kilo Cloud


Reviewed by step-3.7-flash:free · Input: 123.4K · Output: 22.6K · Cached: 199K

@jaylfc
jaylfc merged commit 04ba39b into dev Sep 6, 2026
39 of 41 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant