Skip to content

feat(downloads): relay node-local artifacts through proxies - #608

Merged
Quick104 merged 14 commits into
mainfrom
agent/transcode-download-relay
Aug 12, 2026
Merged

Quick104 merged 14 commits into
mainfrom
agent/transcode-download-relay

Conversation

@Quick104

@Quick104 Quick104 commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Part of #602

Stacked on #607 (agent/distributed-download-jobs). This follow-up removes that PR's shared-artifact-mount requirement while preserving its queueing, allocation, and proxy-delivery work.

Problem

#607 can execute prepared downloads on transcode nodes only when the API, transcode, and proxy processes share the same artifact path. The dev topology intentionally has node-local transcode volumes, so distributed preparation otherwise falls back to the API node.

Approach

  • Keep prepared bytes on the selected transcode node behind bearer-protected opaque artifact IDs; callers never choose or receive a node-local output path.
  • Run the existing playback.PrepareFile pipeline on that node with its live FFmpeg, hardware-acceleration, and device settings, preserving the codec logic shared with streaming.
  • Persist the stable origin node ID, current URL/group snapshot, opaque artifact ID, and size with the durable artifact row. Refresh URL/group from the node pool by stable ID when serving or cleaning up.
  • Prefer a proxy in the transcode origin's group, then relay GET/HEAD/range/conditional requests from proxy to transcode. The established API /file route performs the same authenticated relay as its non-redirecting fallback.
  • Use authenticated HEAD/DELETE for recovery and retention cleanup. Missing or wrong-sized artifacts are deleted and requeued; transient node outages retain the ready locator.
  • Store artifacts inside the existing persistent transcode volume by default and protect that directory from HLS orphan cleanup. No shared artifact mount is required.

Validation

Passed locally:

go test ./internal/downloads ./internal/downloadprepare ./internal/transcodenode ./internal/proxy ./internal/nodepool -count=1
go test ./internal/api/handlers -run 'Download|ProxyPreflight' -count=1 -timeout=60s
go vet ./internal/downloadprepare ./internal/downloads ./internal/transcodenode ./internal/proxy ./internal/nodepool ./internal/api/handlers
golangci-lint run --new-from-merge-base=origin/agent/distributed-download-jobs  # 0 issues
go test ./cmd/silo ./migrations -count=1
make build
make migrate-validate
make verify-local-paths
cd web && pnpm run lint          # 0 errors; existing warnings only
cd web && pnpm run format:check

go test ./... -count=1 passed every changed package except one transcode tracking 250 ms timing assertion during the fully parallel run; that assertion passed 20/20 in isolation. The run also hit two Jellycompat process-lock identity tests and four NVIDIA probe tests. The two Jellycompat failures plus the NVIDIA cache/smoke failures reproduced from the untouched stack base; all affected packages pass their focused change tests. make test-web reported 1,844 passing tests and the same 36 local-storage/appearance baseline failures on both this worktree and the untouched stack base; no web source changed here.

Live dev proof on commit e800c030342d792a53c037f11af7c2cfcfcdc8ce:

  • make dev-deploy rebuilt/recreated the integrated API plus both transcode and both proxy nodes; all five deployed binaries had SHA-256 1b180c7b3e4ca713363900a65fac492f1e58557c764237f9c6be2ae010d05ea7.
  • A real HEVC source requested at the 1 Mbps download preset was prepared on ns12 transcode. Operational logs recorded QSV selecting /dev/dri/renderD128; ffprobe reported H.264 High, 640x360, ~966 kbps video in MP4.
  • The managed proxy route returned 307 to the same-group ns12 proxy and then 200; a range returned 307 -> 206 with Content-Range: bytes 100-199/1210132; HEAD returned 307 -> 200; If-None-Match returned 307 -> 304.
  • Full proxy, full API fallback, and the node-local artifact all matched SHA-256 21ba221d2675cf3df7042173e43e449468dd696cad3b71c3fa98b3f0e377ff5d; both 100-byte range responses matched as well.
  • After deleting the test download and aging the unlinked artifact, startup cleanup called the owning transcode node, removed the node-local file and database row, and recorded the sweep. Test data was removed, all four temporarily enabled nodes were restored disabled, and silo-runtime dev doctor passed.

Risks and compatibility

  • Additive migration only; existing local artifact rows keep empty origin fields and continue using the local path.
  • Proxy tokens carry only the origin URL and opaque artifact ID; MediaPath is forced empty for node-local artifacts.
  • Internal relay clients reject redirects and forward only a small range/representation header allowlist.
  • Prepare POSTs intentionally have no transport deadline because encodes can take hours; their durable lease context owns cancellation. Metadata and byte-relay operations retain bounded response-header waits.

Adversarial review

The self-review found and fixed: the prepare POST incorrectly sharing a 60-second response-header deadline with relay requests; indeterminate response-loss recovery falling back locally and potentially orphaning remote bytes; mismatched/truncated remote artifacts being reaccepted by the idempotent endpoint; partial API relays returning an error after response headers were committed; incomplete remote locators; stale node URLs; redirect following; unsafe header forwarding; and accidental local-path inclusion in proxy tokens. Regression tests cover these cases and the live test exercised creation, hardware preparation, grouped proxy relay, API fallback, ranges, conditionals, and deletion.

AI Disclosure

  • Tool(s): Codex in T3 Code
  • Model(s): gpt-5.6-sol
  • Involvement: fully AI-generated
  • Adversarial review: Reviewed the complete stacked diff for authorization, path isolation, durable recovery, timeout, partial-response, proxy-affinity, and cleanup failures; fixed the issues listed above and validated them with focused tests plus a five-service live deployment.

Summary by CodeRabbit

  • New Features
    • Distributed downloads can be prepared and stored on transcode nodes without shared storage.
    • Downloads securely relay artifacts from their originating node, including range, partial-content, HEAD, and bandwidth-limited requests.
    • Added opaque artifact identifiers, validation, authorization, recovery, and automated cleanup.
  • Bug Fixes
    • Improved recovery when remote preparation is interrupted or artifacts become unavailable.
    • Prevented invalid artifact paths and unauthorized remote access.
    • Preserved local fallback behavior when remote artifact retrieval is unavailable.
  • Documentation
    • Clarified artifact storage, proxy relay behavior, fallback downloads, and restart requirements after changing the transcode directory.

@coderabbitai

coderabbitai Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

You’ve reached a temporary PR review limit under our Fair Usage Limits Policy.

Your recent review volume is higher than typical usage, so adaptive limits are currently applied.

Next review available in: 59 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 8aff036e-cee3-4c6d-9e27-1c88ef677a65

📥 Commits

Reviewing files that changed from the base of the PR and between cfa05ec and bbe2168.

📒 Files selected for processing (26)
  • README.md
  • cmd/silo/main.go
  • internal/api/handlers/downloads.go
  • internal/api/handlers/downloads_test.go
  • internal/config/config.go
  • internal/config/db_loader.go
  • internal/config/db_loader_test.go
  • internal/config/restart_keys.go
  • internal/config/restart_keys_test.go
  • internal/downloadprepare/transport.go
  • internal/downloadprepare/transport_test.go
  • internal/downloads/artifact_repo.go
  • internal/downloads/artifact_repo_test.go
  • internal/downloads/artifact_test.go
  • internal/downloads/artifacts.go
  • internal/downloads/remote_preparer.go
  • internal/downloads/remote_preparer_test.go
  • internal/downloads/service.go
  • internal/downloads/service_remote_test.go
  • internal/proxy/download_test.go
  • internal/proxy/server.go
  • internal/streamtoken/token.go
  • internal/transcodenode/server.go
  • internal/transcodenode/server_test.go
  • migrations/sql/20260812033954_add_download_artifact_origin.sql
  • migrations/sql/20260812163547_add_download_artifact_orphan_fairness_index.sql
📝 Walkthrough

Walkthrough

This change adds distributed prepared-download support. Transcode nodes store artifacts locally, expose authenticated artifact endpoints, persist origin metadata, and relay data through API and proxy paths without a shared artifact mount.

Changes

Distributed prepared downloads

Layer / File(s) Summary
Artifact identity and node API
README.md, docs/superpowers/specs/..., internal/downloadprepare/..., internal/transcodenode/..., internal/streamtoken/token.go, internal/downloads/artifact.go, migrations/sql/...
Preparation uses opaque artifact IDs and server-controlled paths. Transcode nodes provide authenticated artifact routes. Origin metadata is stored in the database and download claims.
Artifact persistence and recovery
internal/downloads/artifact_repo.go, internal/downloads/artifacts.go, internal/downloads/remote_preparer.go, internal/downloads/*_test.go
Preparation returns local or remote artifact locators. Recovery, requeue, eviction, and orphan cleanup operate through the owning node.
Origin-aware proxy routing
internal/nodepool/planner.go, internal/api/handlers/downloads.go, internal/api/handlers/downloads_test.go
Proxy planning prefers the artifact origin group. Redirect tokens and cache keys identify remote artifact targets.
Remote artifact relay serving
internal/downloads/service.go, internal/proxy/server.go, internal/downloads/bandwidth.go, internal/proxy/*_test.go, internal/downloads/service_remote_test.go
Download services and proxies relay authenticated remote artifacts with range, HEAD, response, status, timeout, and bandwidth handling. Local file serving remains supported.

Estimated code review effort: 5 (Critical) | ~120 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant DownloadService
  participant ProxyServer
  participant TranscodeNode
  Client->>DownloadService: Request prepared download
  DownloadService->>ProxyServer: Redirect with artifact token
  ProxyServer->>TranscodeNode: Authenticated artifact request
  TranscodeNode-->>ProxyServer: Artifact response
  ProxyServer-->>Client: Relayed response
Loading

Possibly related PRs

Suggested labels: v1

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 19.23% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the primary change: relaying node-local download artifacts through proxy nodes.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch agent/transcode-download-relay

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

@Quick104

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot added the v1.0 Silo v1 scope - auto-adds to the Silo v1 project label Aug 12, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

if !applied {
slog.WarnContext(ctx, "download artifact ready skipped; lease lost", "component", "downloads", "artifact_id", a.ID)
return

P1 Badge Preserve remote locators after losing the readiness fence

When a long-running remote encode loses its lease and the replacement worker selects another transcode node, this return discards the only locator for the completed artifact on the first node. The replacement may successfully publish its own copy, but the first copy has no database row through which cleanup can discover it, while the node's orphan sweeper deliberately protects the artifact directory; repeated lease or database failures can therefore leak full media files until the node disk fills. Persist attempt ownership or safely delete the abandoned remote artifact when the fence rejects the commit.

AGENTS.md reference: AGENTS.md:L12-L14

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread internal/downloads/service.go Resolved
Comment thread internal/downloads/remote_preparer.go Resolved
Comment thread internal/transcodenode/server.go Resolved
Comment thread internal/downloads/artifacts.go Resolved
Comment thread internal/downloads/service.go Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Nitpick comments (2)
internal/transcodenode/server_test.go (1)

156-165: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert the reported FileSize against the real file.

result.FileSize < 0 cannot fail. FileSize is int64, and the stub FFmpeg script creates an empty file, so both a correct result and a missing file_size field decode to 0. The new prepare contract reports the artifact size to the API, so the test should compare against the file on disk.

♻️ Proposed test strengthening
-	if _, err := os.Stat(outputPath); err != nil {
+	info, err := os.Stat(outputPath)
+	if err != nil {
 		t.Fatalf("prepared output: %v", err)
 	}
 	var result downloadprepare.Result
 	if err := json.NewDecoder(rr.Body).Decode(&result); err != nil {
 		t.Fatal(err)
 	}
-	if result.ArtifactID != "artifact-1" || result.FileSize < 0 || strings.Contains(rr.Body.String(), artifactDir) {
+	if result.ArtifactID != "artifact-1" || result.FileSize != info.Size() || strings.Contains(rr.Body.String(), artifactDir) {
 		t.Fatalf("prepare result = %+v body=%s", result, rr.Body.String())
 	}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/transcodenode/server_test.go` around lines 156 - 165, Strengthen the
assertion in the prepare-result test after decoding result by obtaining the
actual size of prepared outputPath with os.Stat and comparing result.FileSize to
that size. Replace the ineffective result.FileSize < 0 check while preserving
the ArtifactID and artifactDir assertions.
internal/nodepool/planner_test.go (1)

594-606: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add coverage for the group-fallback branch.

The test proves that a matching group wins. The new len(candidates) == 0 fallback in PlanDownload is untested. Add a case where the preferred group matches no healthy proxy and assert that the planner still returns an eligible proxy from another group.

♻️ Proposed additional test
func TestPlanDownloadFallsBackWhenOriginGroupHasNoProxy(t *testing.T) {
	groupA := "host-a"
	proxies := NewProxyPool()
	proxies.SetNodes([]*Node{
		{URL: "http://proxy-a", Group: &groupA, Enabled: true, Healthy: true},
	})
	planner := NewPlanner(proxies, NewTranscodePool())
	plan := planner.PlanDownload("download-fallback", "host-missing")
	if plan.ProxyNode == nil || plan.ProxyNode.URL != "http://proxy-a" {
		t.Fatalf("plan = %+v, want proxy-a fallback", plan)
	}
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/nodepool/planner_test.go` around lines 594 - 606, Add a test
alongside TestPlanDownloadPrefersArtifactOriginGroup that calls PlanDownload
with an origin group having no healthy matching proxy, while another eligible
proxy exists in a different group; assert the returned plan uses that fallback
proxy.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/api/handlers/downloads.go`:
- Line 576: Update the target validation guard in the download handler so
artifact-backed targets with OriginArtifactID require a non-empty, trimmed
OriginNodeURL; reject incomplete artifact locators for proxy redirect while
preserving valid path-target handling so the caller can serve the bytes
fallback.

In `@internal/downloads/artifacts.go`:
- Around line 421-427: Update the validation condition in the prepared artifact
flow around remoteFieldsPresent to reject non-positive file sizes by changing
the FileSize check from negative-only to <= 0. Preserve the existing
invalid-locator warning, failJob call, and return behavior.

In `@internal/downloads/service_remote_test.go`:
- Around line 14-20: In the origin httptest handlers for
internal/downloads/service_remote_test.go lines 14-20 and
internal/proxy/download_test.go lines 64-73, replace each handler-side t.Fatalf
assertion for path/authorization and Range validation with t.Errorf, write an
explicit error HTTP status, and return immediately so the relay receives a
deliberate failure response instead of a transport error.

In `@migrations/sql/20260812033954_add_download_artifact_origin.sql`:
- Around line 7-8: Add NOT VALID to the download_artifacts_origin_check
constraint so creating it does not scan and block writes during this migration.
Leave validation to a subsequent Goose migration that explicitly validates the
existing constraint.

---

Nitpick comments:
In `@internal/nodepool/planner_test.go`:
- Around line 594-606: Add a test alongside
TestPlanDownloadPrefersArtifactOriginGroup that calls PlanDownload with an
origin group having no healthy matching proxy, while another eligible proxy
exists in a different group; assert the returned plan uses that fallback proxy.

In `@internal/transcodenode/server_test.go`:
- Around line 156-165: Strengthen the assertion in the prepare-result test after
decoding result by obtaining the actual size of prepared outputPath with os.Stat
and comparing result.FileSize to that size. Replace the ineffective
result.FileSize < 0 check while preserving the ArtifactID and artifactDir
assertions.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 232fff46-309b-46b5-9d0d-eeddfa9a3556

📥 Commits

Reviewing files that changed from the base of the PR and between ee73310 and e800c03.

📒 Files selected for processing (26)
  • README.md
  • docs/superpowers/specs/2026-06-18-offline-sync-mobile-design.md
  • internal/api/handlers/downloads.go
  • internal/api/handlers/downloads_test.go
  • internal/downloadprepare/transport.go
  • internal/downloadprepare/transport_test.go
  • internal/downloads/artifact.go
  • internal/downloads/artifact_repo.go
  • internal/downloads/artifact_repo_test.go
  • internal/downloads/artifact_test.go
  • internal/downloads/artifacts.go
  • internal/downloads/bandwidth.go
  • internal/downloads/remote_preparer.go
  • internal/downloads/remote_preparer_test.go
  • internal/downloads/repo_managed_test.go
  • internal/downloads/service.go
  • internal/downloads/service_quota_test.go
  • internal/downloads/service_remote_test.go
  • internal/nodepool/planner.go
  • internal/nodepool/planner_test.go
  • internal/proxy/download_test.go
  • internal/proxy/server.go
  • internal/streamtoken/token.go
  • internal/transcodenode/server.go
  • internal/transcodenode/server_test.go
  • migrations/sql/20260812033954_add_download_artifact_origin.sql

Comment thread internal/api/handlers/downloads.go Resolved
Comment thread internal/downloads/artifacts.go Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 91da29c0ba

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread internal/downloads/artifact_repo.go Resolved
Comment thread internal/downloads/artifact_repo.go Resolved
Comment thread internal/downloads/remote_preparer.go Resolved
@Quick104

Copy link
Copy Markdown
Contributor Author

Addressed and resolved every current review thread in 58aa29e03.

The final pass also covers the non-inline review notes: exact prepared file-size assertion, proxy-group fallback coverage, changed-line lint errors, and a fair interleaved orphan batch that still lets healthy origins use spare capacity.

Validation on the isolated dev-builder sandbox download-relay-608-final:

  • go test ./..., go vet ./..., settings bindings, Goose validation, frontend lint/format, and the remote frontend/backend build passed.
  • DB-backed requeue and cleanup-fairness tests executed against the sandbox database and passed.
  • A real prepared download ran on the sandbox transcode node, then served through the same-group proxy (307 -> 200); API/proxy SHA-256 matched, range returned 206 with 3,996 bytes, and stale If-Match returned 412.
  • Removing the origin produced 409, atomically moved both linked downloads to preparing, regenerated successfully, and drained the durable cleanup queue.
  • Final sandbox doctor is green for API, frontend, database, proxy, and transcode.

The dev-builder host has no compatible GPU, so this run verified distributed routing and shared codec-selection behavior with the documented software fallback; prior QSV-capable deployment evidence on the preceding head verified the hardware branch. The implementation calls the same playback.PrepareFile path in both cases.

@codex review
@coderabbitai review

@coderabbitai

coderabbitai Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor
🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- PR metadata ---'
gh pr view 608 --repo Silo-Server/silo-server --json number,headRefOid,baseRefOid,files --jq '{number, headRefOid, baseRefOid, changed_files: [.files[].path]}'

printf '%s\n' '--- Diff statistics ---'
git diff --stat "$(git merge-base HEAD origin/HEAD)" HEAD 2>/dev/null || git diff --stat HEAD~1 HEAD

printf '%s\n' '--- High-risk file outlines ---'
for file in \
  internal/downloadprepare/transport.go \
  internal/downloads/artifacts.go \
  internal/downloads/remote_preparer.go \
  internal/downloads/service.go \
  internal/proxy/server.go \
  internal/transcodenode/server.go \
  internal/api/handlers/downloads.go \
  internal/nodepool/planner.go; do
  if [ -f "$file" ]; then
    echo "### $file"
    ast-grep outline "$file" --items all
  fi
done

printf '%s\n' '--- Artifact route and relay call sites ---'
rg -n -C 3 --glob '*.go' \
  'ValidArtifactID|Open\(|ResolveArtifact|StatArtifact|DeleteArtifact|serveFileTarget|relayDownload|DownloadArtifactID|PlanDownload\(' \
  internal

Length of output: 118171


🏁 Script executed:

#!/bin/bash
set -euo pipefail

show() {
  local file="$1"
  local range="$2"
  echo "### ${file}:${range}"
  sed -n "${range}p" "$file"
}

show internal/downloadprepare/transport.go '29,320'
show internal/downloads/service.go '1080,1225'
show internal/proxy/server.go '165,266'
show internal/api/handlers/downloads.go '542,684'
show internal/downloads/artifacts.go '300,430'
show internal/downloads/artifacts.go '500,850'
show internal/downloads/artifact_repo.go '430,540'
show internal/transcodenode/server.go '417,580'
show internal/nodepool/planner.go '114,178'

for file in migrations/sql/20260812033954_add_download_artifact_origin.sql \
            migrations/sql/20260812045218_add_download_artifact_orphans.sql \
            migrations/sql/20260812144845_validate_download_artifact_origin.sql; do
  echo "### $file"
  cat "$file"
done

printf '%s\n' '--- Focused test names and assertions ---'
for file in \
  internal/downloadprepare/transport_test.go \
  internal/downloads/service_remote_test.go \
  internal/proxy/download_test.go \
  internal/api/handlers/downloads_test.go \
  internal/downloads/artifact_repo_test.go \
  internal/downloads/remote_preparer_test.go \
  internal/transcodenode/server_test.go; do
  echo "### $file"
  rg -n -A4 -B1 '^func Test.*(Artifact|Remote|Proxy|Download|Cleanup|Orphan|Relay|Response|Head|Prepare)' "$file"
done

Length of output: 79150


🏁 Script executed:

#!/bin/bash
set -euo pipefail

show() {
  echo "### $1:$2"
  sed -n "${2}p" "$1"
}

show internal/downloads/remote_preparer.go '20,170'
show internal/downloads/artifacts.go '430,520'
show internal/proxy/server.go '30,90'
show internal/api/handlers/downloads.go '30,105'
show internal/api/router.go '1,180'
show internal/transcodenode/path_authorizer.go '1,180'
show internal/nodesessions/tracker.go '1,240'
show internal/nodepool/planner.go '235,281'
show internal/downloads/artifact_repo.go '1,145'
show internal/downloads/artifact_repo.go '145,300'

printf '%s\n' '--- Redirect and locator validation coverage ---'
rg -n -C 3 --glob '*.go' \
  '(CheckRedirect|ErrUseLastResponse|redirect|invalid node URL|OriginNodeURL|OriginArtifactID|result\.ArtifactID|FileSize !=|ReleaseSession|Remove\()' \
  internal/downloadprepare internal/downloads internal/proxy internal/api/handlers internal/nodepool internal/nodesessions \
  -g '*_test.go' -g '*.go'

printf '%s\n' '--- HTTP client assignment sites ---'
rg -n -C 3 --glob '*.go' '(httpClient:|\.httpClient\s*=|proxyHTTPClient|SetOfflineDeps)' internal

Length of output: 133405


@Quick104, I completed the review of 58aa29e0396fb22de6b72e31ec1f5d6e2ed21b56.

I found no actionable issues.

The reviewed paths validate opaque artifact IDs and node URLs. They block redirects. They preserve range and conditional responses. They avoid origin filesystem-path exposure. They verify remote artifact identity and size. They protect remote cleanup against indeterminate readiness writes. They also release proxy reservations for failed preflight and HEAD requests.

I did not rerun the runtime validation in this inspection sandbox. The reported deployment and test validation covers the remaining environment-dependent behavior.

⚠️ Action not completed

Review rate limited.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@Quick104

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 58aa29e039

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread internal/proxy/server.go Resolved
Comment thread internal/downloads/remote_preparer.go Resolved
@Quick104

Copy link
Copy Markdown
Contributor Author

Final Codex findings are addressed in 9abdbee8c:

  • Artifact relay reads now have a shared two-minute per-upstream-read idle watchdog. The watchdog cancels the node request and closes its body when a read stalls, while explicitly excluding downstream backpressure and configured bandwidth-throttle sleeps.
  • Resolved node URLs/groups are fenced and persisted. Disabled origins are looked up in the authoritative repository before requeue/cleanup, so an administrative URL change cannot strand cleanup on the old endpoint.

Exact-head validation on isolated dev-builder sandbox download-relay-608-final:

  • repeated race-detector coverage for stalled/progressing relay bodies passed;
  • DB-backed refreshed-locator, transactional requeue, and cleanup-fairness tests passed;
  • go test ./... and go vet ./... passed remotely;
  • exact-head backend rebuilt across the sandbox API/proxy/transcode services and final doctor is fully healthy.

@coderabbitai review

@Quick104

Copy link
Copy Markdown
Contributor Author

@codex review

@coderabbitai

coderabbitai Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor
🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

commit="$(git rev-parse 9abdbee8c)"
printf '%s\n' '--- Commit ---'
git show --no-ext-diff --format=fuller --stat "$commit"

printf '%s\n' '--- Changed files ---'
git diff-tree --no-commit-id --name-only -r "$commit"

printf '%s\n' '--- Changed-code outlines ---'
git diff-tree --no-commit-id --name-only -r "$commit" | while IFS= read -r file; do
  case "$file" in
    *.go)
      echo "### $file"
      ast-grep outline "$file" --items all
      ;;
  esac
done

printf '%s\n' '--- Exact diff ---'
git show --no-ext-diff --format= --find-renames "$commit" -- \
  'internal/**/*.go' \
  'migrations/**/*.sql'

Length of output: 53621


🏁 Script executed:

#!/bin/bash
set -euo pipefail

show() {
  local file="$1"
  local range="$2"
  echo "### ${file}:${range}"
  sed -n "${range}p" "$file"
}

show internal/downloadprepare/transport.go '200,390'
show internal/downloads/artifacts.go '130,180'
show internal/downloads/artifacts.go '340,430'
show internal/downloads/artifacts.go '520,590'
show internal/downloads/artifacts.go '725,870'
show internal/downloads/artifact_repo.go '240,365'
show internal/downloads/artifact_repo.go '430,570'
show internal/downloads/remote_preparer.go '20,185'

printf '%s\n' '--- Node-aware preparer wiring and HTTPPreparer.Open consumers ---'
rg -n -C 4 --glob '*.go' \
  '(SetOriginLookup\s*\(|HTTPPreparer\{|\.\s*Open\s*\(|Open\(ctx,.*artifact|Open\(.*artifact)' \
  cmd internal

printf '%s\n' '--- Remote requeue and cleanup definitions/call sites ---'
rg -n -C 4 --glob '*.go' \
  '(RequeueRemote\s*\(|EnqueueRemoteOrphan\s*\(|PrepareRemoteOrphanCleanup\s*\(|DeleteArtifact\s*\(ctx,.*artifact)' \
  internal/downloads

printf '%s\n' '--- Focused test bodies ---'
show internal/downloadprepare/transport_test.go '105,190'
show internal/downloads/artifact_repo_test.go '200,355'
show internal/downloads/remote_preparer_test.go '100,175'

Length of output: 127209


@Quick104, I reviewed 9abdbee8c.

I found no actionable issues.

idleReadCloser applies the two-minute timeout only while an upstream Read is blocked. It cancels the relay request and closes the upstream body on timeout. The API and proxy relay paths both use HTTPPreparer.Open and close the response body.

The origin locator path now resolves the current node URL and group before serving and recovery checks. RefreshRemoteLocator fences the database update with the ready status, node ID, and artifact ID. Disabled nodes use the authoritative node record for cleanup. Deleted nodes retain the persisted locator as the cleanup target.

The focused tests cover stalled reads, continued read progress, persisted locator refresh, transactional requeue, and cleanup through a disabled origin's current URL.

I did not rerun the reported runtime validation in this inspection sandbox.

⚠️ Action not completed

Review rate limited.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9abdbee8c1

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread internal/downloads/service.go Resolved
Comment thread internal/transcodenode/server.go Resolved
@Quick104

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9abdbee8c1

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread internal/downloadprepare/transport.go Resolved
@Quick104

Copy link
Copy Markdown
Contributor Author

Final follow-up fixes are pushed in 87e342434 and all three current review threads are resolved.

Exact-head validation on isolated dev-builder sandbox download-relay-608-final:

  • API, frontend, database, proxy, and transcode node are all healthy;
  • DB-backed on-demand 404 recovery proves the artifact is queued, the linked completed download is reset to preparing, and the remote cleanup locator is persisted atomically;
  • transactional requeue and cleanup-fairness DB tests pass;
  • stalled prepare-result and relay-body coverage passes under go test -race -count=3;
  • transcode-node path-pinning suite and focused go vet pass;
  • full no-DB Go suite passed except one transient existing scanner text file busy test, which passed immediately in isolation; the full DB sweep also exposed unrelated cloned-fixture schema/seed drift, while every changed-surface DB test passed.

The previously completed distributed E2E remains applicable: transcode-node preparation, same-group proxy relay, matching API/proxy hashes, range/conditional responses, origin-removal requeue, regeneration, and cleanup drain. This final patch changes only recovery timing, path consistency, and transport liveness.

@codex review
@coderabbitai review

@coderabbitai

coderabbitai Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor
🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

commit="$(git rev-parse 87e342434)"

printf '%s\n' '--- commit and changed files ---'
git show --no-ext-diff --format=fuller --stat "$commit"
git diff-tree --no-commit-id --name-only -r "$commit"

printf '%s\n' '--- changed Go-file outlines ---'
git diff-tree --no-commit-id --name-only -r "$commit" | while IFS= read -r file; do
  case "$file" in
    *.go)
      echo "### $file"
      ast-grep outline "$file" --items all
      ;;
  esac
done

printf '%s\n' '--- exact diff ---'
git show --no-ext-diff --format= --find-renames "$commit" -- 'internal/**/*.go' 'migrations/**/*.sql'

printf '%s\n' '--- recovery, locator, and relay call sites ---'
rg -n -C 4 --glob '*.go' \
  '(RequeueRemote|RefreshRemoteLocator|PrepareRemoteOrphanCleanup|EnqueueRemoteOrphan|idleReadCloser|Open\(ctx|StatArtifact|DeleteArtifact|ResolveArtifact|artifact.*404|StatusNotFound)' \
  internal

Length of output: 186279


🏁 Script executed:

#!/bin/bash
set -euo pipefail

commit="$(git rev-parse 87e342434)"
base="${commit}^"

printf '%s\n' '--- changed files ---'
git diff-tree --no-commit-id --name-only -r "$commit"

printf '%s\n' '--- changed hunk locations ---'
git diff --unified=0 "$base" "$commit" -- 'internal/**/*.go' 'migrations/**/*.sql' |
  rg -n '^\+\+\+|^@@'

printf '%s\n' '--- exact changed diff ---'
git diff --no-ext-diff --unified=80 "$base" "$commit" -- 'internal/**/*.go' 'migrations/**/*.sql'

printf '%s\n' '--- focused tests in changed files ---'
git diff-tree --no-commit-id --name-only -r "$commit" |
  rg '_test\.go$' |
  while IFS= read -r file; do
    echo "### $file"
    rg -n -A55 -B5 '^func Test' "$file"
  done

Length of output: 123412


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- transport idle wrapper and result decoding ---'
ast-grep outline internal/downloadprepare/transport.go --items all
rg -n -A100 -B20 'func newIdleReadCloser|type idleReadCloser|func \(.*idleReadCloser.*Read|func decodeResult|func \(p HTTPPreparer\) readIdleTimeout' internal/downloadprepare/transport.go

printf '%s\n' '--- remote requeue transaction and cleanup enqueue ---'
rg -n -A150 -B20 'func \(.*\) RequeueRemote|func \(.*\) EnqueueRemoteOrphan|func \(.*\) requeueRemoteArtifactNow' \
  internal/downloads/artifact_repo.go internal/downloads/artifacts.go

printf '%s\n' '--- file-serving error mapping ---'
rg -n -A65 -B20 'func \(h \*DownloadHandler\) writeDownloadFileError|serveDownloadBytes\(' \
  internal/api/handlers/downloads.go

printf '%s\n' '--- transcode server initialization and pinned directories ---'
rg -n -A80 -B20 'func NewServer|transcodeDir:|artifactRoot:|func \(s \*Server\) activeSessionIDs' \
  internal/transcodenode

Length of output: 70872


@Quick104, I reviewed 87e342434.

I found no actionable issues.

The idle watchdog now covers the prepare-result body and relay bodies. It cancels the upstream request only when an upstream read stalls.

A remote artifact 404 now performs a synchronous, fenced requeue. The transaction resets linked downloads and persists the cleanup locator. The request then returns ErrDownloadNotActive, which the API maps to HTTP 409.

The transcode node now uses the startup-pinned transcode directory for session output and cleanup. This prevents a configuration reload from splitting session lifecycle operations across paths.

I did not run runtime validation in this inspection sandbox. The added focused tests cover the changed behaviors.

⚠️ Action not completed

Review rate limited.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@Quick104

Copy link
Copy Markdown
Contributor Author

Changed-line lint is fixed in cfa05eca0: both newly touched session cleanup calls now report os.RemoveAll failures with request-scoped context. The exact committed head has been rebuilt on dev-builder; API, frontend, database, proxy, and transcode node are healthy, and the transcode/downloadprepare suites plus focused vet pass there.

@codex review
@coderabbitai review

@coderabbitai

coderabbitai Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor
🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

commit="$(git rev-parse cfa05eca0)"
base="${commit}^"

printf '%s\n' '--- Commit ---'
git show --no-ext-diff --format=fuller --stat "$commit"

printf '%s\n' '--- Changed files ---'
git diff-tree --no-commit-id --name-only -r "$commit"

printf '%s\n' '--- Exact diff ---'
git diff --no-ext-diff --find-renames --unified=80 "$base" "$commit" -- 'internal/**/*.go'

printf '%s\n' '--- Changed Go-file outlines ---'
git diff-tree --no-commit-id --name-only -r "$commit" |
  while IFS= read -r file; do
    case "$file" in
      *.go)
        echo "### $file"
        ast-grep outline "$file" --items all
        ;;
    esac
  done

printf '%s\n' '--- os.RemoveAll call sites in affected areas ---'
rg -n -C 8 --glob '*.go' 'os\.RemoveAll\s*\(' internal/transcodenode internal/downloadprepare internal/downloads

Length of output: 22282


@Quick104, I reviewed cfa05eca0.

I found no actionable issues.

handleStop now logs failed session-directory cleanup with the request context and session ID.

handleForceReload now logs failed cleanup for each stopped session with the request context and session ID.

The change keeps the existing best-effort cleanup behavior. It does not change session removal, job accounting, recipe cleanup, tracker cleanup, or HTTP status handling.

I did not rerun the reported sandbox validation.

✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (4)
internal/downloads/artifacts.go (1)

298-300: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Remove the trailing blank line before the closing brace.

gofmt removes a blank line that directly precedes a closing brace. Line 299 leaves the function body with that blank line. The coding guidelines require gofmt-clean Go code.

♻️ Proposed fix
 	}
-
 }
As per coding guidelines: "Keep Go code `gofmt` and `goimports` clean."
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/downloads/artifacts.go` around lines 298 - 300, Remove the trailing
blank line immediately before the closing brace in the affected function in
artifacts.go, then run gofmt to ensure the file remains format-clean.

Source: Coding guidelines

cmd/silo/main.go (1)

924-931: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low value

Consider passing ctx instead of context.Background().

These two calls now terminate startup on error. They still run with context.Background(), so they carry no deadline or cancellation from the startup context. The pool's own connection timeouts bound the call, so this is not a defect. Using ctx keeps the startup path cancellable and consistent with the other startup queries.

♻️ Proposed change
-		proxyNodes, err := nodeRepo.ListEnabled(context.Background(), nodepool.NodeTypeProxy)
+		proxyNodes, err := nodeRepo.ListEnabled(ctx, nodepool.NodeTypeProxy)
 		if err != nil {
 			log.Fatalf("load enabled proxy nodes: %v", err)
 		}
-		transcodeNodes, err := nodeRepo.ListEnabled(context.Background(), nodepool.NodeTypeTranscode)
+		transcodeNodes, err := nodeRepo.ListEnabled(ctx, nodepool.NodeTypeTranscode)
 		if err != nil {
 			log.Fatalf("load enabled transcode nodes: %v", err)
 		}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@cmd/silo/main.go` around lines 924 - 931, Update both nodeRepo.ListEnabled
calls in the startup flow to pass the existing ctx instead of
context.Background(), preserving the current node types and error handling while
allowing startup cancellation and deadlines to propagate.
internal/downloads/artifact_repo.go (1)

466-498: 🚀 Performance & Scalability | 🔵 Trivial

Fairness query scans the whole due set.

The CTE ranks every due row before LIMIT applies. This is fine while the queue stays small. If a node stays unreachable for a long time, the queue grows and each sweep pays a full scan plus sort. Consider adding an index on (origin_node_id, origin_node_url, attempts, created_at, id) if you observe the sweep slowing down.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/downloads/artifact_repo.go` around lines 466 - 498, The
ListRemoteOrphansDue query ranks and sorts the entire due queue before applying
LIMIT, so add a supporting database index on origin_node_id, origin_node_url,
attempts, created_at, and id for download_artifact_orphans. Update the relevant
schema or migration used by ArtifactRepository, preserving the existing query
behavior and due-row filtering.
internal/downloads/artifact_repo_test.go (1)

318-324: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Rename orchans to orphans.

The variable name is a typo. It appears in several new tests and reads as a different word than the queue it holds.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/downloads/artifact_repo_test.go` around lines 318 - 324, Rename the
variable orchans to orphans throughout the affected tests, including its
declaration and all references, while preserving the existing assertions and
behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/downloads/artifact_repo_test.go`:
- Around line 447-465: Before calling ListRemoteOrphansDue in the fairness
assertion, update all unrelated due rows in download_artifact_orphans to be no
longer due, while preserving the test fixtures for origin nodes 31001 and 31002.
Ensure the global limit only considers these fixtures so the existing seen-count
assertion remains valid.

In `@internal/downloads/artifacts.go`:
- Around line 154-161: Update the error handling around resolveRemoteArtifact in
the download readiness flow so ErrArtifactOriginRemoved is wrapped with
ErrDownloadNotActive even when requeueRemoteArtifact does not apply, ensuring
writeDownloadFileError maps the response to HTTP 409. Preserve the existing
requeue behavior and add coverage for the non-requeued origin-removed path.

In `@migrations/sql/20260812045218_add_download_artifact_orphans.sql`:
- Around line 2-14: The orphan locator validation is inconsistent with the
source guard for negative origin node IDs. Update requeueRemoteArtifactNow to
reject OriginNodeID <= 0, or equivalently add the same positive-ID requirement
to download_artifacts_origin_check, so invalid IDs cannot reach
download_artifact_orphans_locator_check.

---

Nitpick comments:
In `@cmd/silo/main.go`:
- Around line 924-931: Update both nodeRepo.ListEnabled calls in the startup
flow to pass the existing ctx instead of context.Background(), preserving the
current node types and error handling while allowing startup cancellation and
deadlines to propagate.

In `@internal/downloads/artifact_repo_test.go`:
- Around line 318-324: Rename the variable orchans to orphans throughout the
affected tests, including its declaration and all references, while preserving
the existing assertions and behavior.

In `@internal/downloads/artifact_repo.go`:
- Around line 466-498: The ListRemoteOrphansDue query ranks and sorts the entire
due queue before applying LIMIT, so add a supporting database index on
origin_node_id, origin_node_url, attempts, created_at, and id for
download_artifact_orphans. Update the relevant schema or migration used by
ArtifactRepository, preserving the existing query behavior and due-row
filtering.

In `@internal/downloads/artifacts.go`:
- Around line 298-300: Remove the trailing blank line immediately before the
closing brace in the affected function in artifacts.go, then run gofmt to ensure
the file remains format-clean.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: bc6958a4-7140-44bf-99e3-6c7c246b4456

📥 Commits

Reviewing files that changed from the base of the PR and between e800c03 and cfa05ec.

📒 Files selected for processing (30)
  • README.md
  • cmd/silo/main.go
  • internal/api/handlers/downloads.go
  • internal/api/handlers/downloads_test.go
  • internal/config/admin_settings.go
  • internal/config/config.go
  • internal/config/db_loader.go
  • internal/config/restart_keys.go
  • internal/config/restart_keys_test.go
  • internal/config/yaml_import.go
  • internal/downloadprepare/transport.go
  • internal/downloadprepare/transport_test.go
  • internal/downloads/artifact_repo.go
  • internal/downloads/artifact_repo_test.go
  • internal/downloads/artifact_test.go
  • internal/downloads/artifacts.go
  • internal/downloads/model.go
  • internal/downloads/remote_preparer.go
  • internal/downloads/remote_preparer_test.go
  • internal/downloads/service.go
  • internal/downloads/service_remote_test.go
  • internal/nodepool/planner.go
  • internal/nodepool/planner_test.go
  • internal/proxy/download_test.go
  • internal/proxy/server.go
  • internal/transcodenode/server.go
  • internal/transcodenode/server_test.go
  • migrations/sql/20260812033954_add_download_artifact_origin.sql
  • migrations/sql/20260812045218_add_download_artifact_orphans.sql
  • migrations/sql/20260812144845_validate_download_artifact_origin.sql
🚧 Files skipped from review as they are similar to previous changes (9)
  • migrations/sql/20260812033954_add_download_artifact_origin.sql
  • README.md
  • internal/downloads/artifact_test.go
  • internal/nodepool/planner.go
  • internal/downloads/remote_preparer_test.go
  • internal/proxy/server.go
  • internal/api/handlers/downloads.go
  • internal/downloads/service.go
  • internal/downloadprepare/transport.go

Comment thread internal/downloads/artifacts.go Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: cfa05eca03

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread internal/downloads/artifacts.go Resolved
Comment thread internal/downloadprepare/transport.go Resolved
@Quick104

Copy link
Copy Markdown
Contributor Author

All findings from the latest CodeRabbit and Codex passes are addressed in 213eaa118, and every review thread is resolved.

Additional hardening:

  • zero-byte complete remote locators are durably queued for cleanup before retry;
  • stalled DELETE error bodies use the shared idle watchdog and preserve ErrRelayReadIdle;
  • stale removed-origin races remain HTTP 409 even when the requeue fence no longer applies;
  • negative node IDs are rejected before the orphan transaction;
  • the fairness test isolates its own fixtures without mutating unrelated rows;
  • startup pool queries use the cancellable application context;
  • the orphan fairness query has a timestamped supporting index;
  • the noted formatting and test-variable nits are cleaned up.

Exact-head dev-builder evidence:

  • API, frontend, database, proxy, and transcode node healthy;
  • all four changed-surface DB recovery/cleanup tests pass;
  • transport tests pass under go test -race -count=3;
  • focused cmd/download tests and vet pass;
  • Goose validation passes and the new index is present in the sandbox database.

@codex review
@coderabbitai review

@coderabbitai

coderabbitai Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor
🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

commit="$(git rev-parse 213eaa118)"
base="${commit}^"

printf '%s\n' '--- Commit and changed files ---'
git show --no-ext-diff --format=fuller --stat "$commit"
git diff-tree --no-commit-id --name-only -r "$commit"

printf '%s\n' '--- Changed hunk locations ---'
git diff --unified=0 "$base" "$commit" -- \
  'cmd/**/*.go' 'internal/**/*.go' 'migrations/**/*.sql' |
  rg -n '^\+\+\+|^@@'

printf '%s\n' '--- Exact changed diff with context ---'
git diff --no-ext-diff --find-renames --unified=70 "$base" "$commit" -- \
  'cmd/**/*.go' 'internal/**/*.go' 'migrations/**/*.sql'

printf '%s\n' '--- Changed Go-file outlines ---'
git diff-tree --no-commit-id --name-only -r "$commit" |
  while IFS= read -r file; do
    case "$file" in
      *.go)
        echo "### $file"
        ast-grep outline "$file" --items all
        ;;
    esac
  done

printf '%s\n' '--- Targeted definitions, call sites, and tests ---'
rg -n -C 5 --glob '*.go' \
  '(ErrRelayReadIdle|idleReadCloser|ReadIdleTimeout|DeleteArtifact\s*\(|RequeueRemote\s*\(|EnqueueRemoteOrphan\s*\(|PrepareRemoteOrphanCleanup\s*\(|ListRemoteOrphansDue\s*\(|OriginNodeID|context\.Background\(\)|context\.TODO\(\)|Test.*(Orphan|Remote|Relay|Delete|Removed|Fair))' \
  cmd internal

printf '%s\n' '--- Changed migration content ---'
git diff-tree --no-commit-id --name-only -r "$commit" |
  rg '^migrations/sql/.*\.sql$' |
  while IFS= read -r file; do
    echo "### $file"
    cat "$file"
  done

Length of output: 180840


🏁 Script executed:

#!/bin/bash
set -euo pipefail

commit="$(git rev-parse 213eaa118)"
base="${commit}^"

printf '%s\n' '--- Changed files ---'
git diff-tree --no-commit-id --name-only -r "$commit"

printf '%s\n' '--- Commit diff ---'
git diff --no-ext-diff --unified=35 "$base" "$commit" -- \
  'cmd/silo/main.go' \
  'internal/downloadprepare/transport.go' \
  'internal/downloadprepare/transport_test.go' \
  'internal/downloads/artifact_repo.go' \
  'internal/downloads/artifact_repo_test.go' \
  'internal/downloads/artifacts.go' \
  'internal/downloads/artifact_test.go' \
  'internal/downloads/remote_preparer.go' \
  'internal/downloads/remote_preparer_test.go' \
  'migrations/sql/20260812163547_add_download_artifact_orphan_fairness_index.sql'

printf '%s\n' '--- Definitions and implementations in affected files ---'
for file in \
  internal/downloadprepare/transport.go \
  internal/downloads/artifact_repo.go \
  internal/downloads/artifacts.go \
  internal/downloads/remote_preparer.go \
  cmd/silo/main.go; do
  if [ -f "$file" ]; then
    echo "### $file"
    ast-grep outline "$file" --items all
  fi
done

printf '%s\n' '--- Focused source slices ---'
rg -n -A110 -B20 \
  'func \(p HTTPPreparer\) Delete|func \(.*idleReadCloser.*Read|func newIdleReadCloser|func \(.*\) EnqueueRemoteOrphan|func \(.*\) ListRemoteOrphansDue|func \(.*\) RequeueRemote|func \(.*\) requeueRemoteArtifactNow|func \(.*\) DeleteArtifact|func \(.*\) ResolveArtifact' \
  internal/downloadprepare/transport.go \
  internal/downloads/artifact_repo.go \
  internal/downloads/artifacts.go \
  internal/downloads/remote_preparer.go

printf '%s\n' '--- Focused changed tests ---'
for file in \
  internal/downloadprepare/transport_test.go \
  internal/downloads/artifact_repo_test.go \
  internal/downloads/artifact_test.go \
  internal/downloads/remote_preparer_test.go; do
  if [ -f "$file" ]; then
    echo "### $file"
    git diff --unified=25 "$base" "$commit" -- "$file"
  fi
done

printf '%s\n' '--- Direct callers of changed artifact methods ---'
rg -n -C 4 --glob '*.go' \
  '\.(Delete|Open|RequeueRemote|EnqueueRemoteOrphan|ListRemoteOrphansDue|PrepareRemoteOrphanCleanup)\s*\(' \
  internal/downloadprepare internal/downloads internal/proxy internal/api cmd/silo

Length of output: 230014


@Quick104, I reviewed 213eaa118.

I found no actionable issues.

The invalid remote-result path queues the remote locator for cleanup before the artifact job retries. This includes a zero-byte remote result.

HTTPPreparer.Delete now applies the shared idle-read watchdog to error bodies. responseError preserves ErrRelayReadIdle through error wrapping.

A removed-origin race now returns an error that includes both ErrDownloadNotActive and ErrArtifactOriginRemoved when the requeue fence no longer applies. The API can keep the HTTP 409 result.

Remote requeue rejects zero and negative origin node IDs before it starts the transaction.

The fairness test now uses isolated fixtures. The new orphan index supports the partition ordering used by ListRemoteOrphansDue.

The initial node-pool queries use appCtx. I did not run the reported sandbox validation.

⚠️ Action not completed

Review rate limited.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: 213eaa1182

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@Quick104

Copy link
Copy Markdown
Contributor Author

@codex review\n\nFinal exact-head review requested for 1254f1fe6. All prior threads are addressed; focused tests, race tests, changed-line lint/vet, and two isolated dev-builder distributed deployments are green.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Breezy!

Reviewed commit: 1254f1fe69

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@Quick104

Copy link
Copy Markdown
Contributor Author

@codex review\n\nFinal exact-head review requested for 4ff0fed4a. This incorporates every unique finding from the authenticated local CodeRabbit full-PR pass; changed-surface tests and race tests, lint/vet, and the isolated dev-builder distributed deployment are green.

@cursor

cursor Bot commented Aug 12, 2026

Copy link
Copy Markdown
Contributor

Bugbot is not enabled for your account, so this pull request was not reviewed.

Enable Bugbot in the Cursor dashboard to get automatic reviews on future PRs.

@Quick104

Copy link
Copy Markdown
Contributor Author

@codex review Final exact-head review requested for c0923e4. The three new P2 findings are fixed, replied to, resolved, and verified with three race runs on the rebuilt fresh dev-builder distributed sandbox.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c0923e40c4

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread internal/transcodenode/server.go Resolved
@Quick104

Copy link
Copy Markdown
Contributor Author

@codex review Final exact-head review requested for c8e70db. The concurrent artifact relay P1 is fixed, replied to, resolved, race-tested, and live-tested on the rebuilt isolated dev-builder distributed sandbox.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c8e70db37a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread internal/downloads/artifacts.go Resolved
Comment thread README.md Resolved
Comment thread internal/downloads/service.go Resolved
Comment thread internal/downloadprepare/transport.go Resolved
Comment thread internal/downloads/remote_preparer.go Resolved
Comment thread internal/downloads/artifacts.go Resolved
@Quick104

Copy link
Copy Markdown
Contributor Author

@codex review Final exact-head review requested for 171e630. All six findings from the c8e70db review are fixed, replied to, resolved, race-tested, and live-tested on the rebuilt isolated dev-builder distributed sandbox.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: 171e630a97

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Base automatically changed from agent/distributed-download-jobs to main August 12, 2026 19:08
@Quick104
Quick104 force-pushed the agent/transcode-download-relay branch from 171e630 to bbe2168 Compare August 12, 2026 19:11
@Quick104
Quick104 merged commit 47e45f4 into main Aug 12, 2026
3 of 4 checks passed
@Quick104
Quick104 deleted the agent/transcode-download-relay branch August 12, 2026 19:14

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: bbe21685fc

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +311 to +314
`UPDATE downloads
SET status = 'preparing', bytes_sent = 0, completed_at = NULL,
error_message = '', updated_at = now()
WHERE artifact_id = $1 AND status NOT IN ('cancelled', 'failed', 'revoked')

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Fence stale transfer completion after artifact requeue

When recovery requeues a remote artifact while an ephemeral /file relay is still copying bytes—for example after the origin is disabled or a concurrent size check rejects it—this update moves the linked download to preparing, but the in-flight ServeFile later performs an unconditional UpdateStatus(...completed...) from its stale snapshot. If replacement then exhausts its retries, MarkLinkedDownloadsFailed only updates preparing rows, leaving this download permanently completed while its artifact is failed and unservable. Fresh evidence beyond the prior linked-reset issue is this race with the still-running relay; fence completion on the current artifact state or download generation so the requeue wins.

AGENTS.md reference: AGENTS.md:L12-L14

Useful? React with 👍 / 👎.

Comment on lines +547 to +550
if _, err := tx.Exec(ctx,
`UPDATE download_artifact_orphans
SET attempts = attempts + 1, next_retry_at = now() + interval '2 minutes'
WHERE id = $1`, orphan.ID); err != nil {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Claim orphan rows only while they remain due

When two API replicas run the recurring artifact task concurrently, both can list the same due orphan; the second waits on this row lock until the first commits its two-minute lease, but then unconditionally updates the row again because neither next_retry_at nor the listed attempt is rechecked. Both replicas consequently report the locator as claimed and issue the same remote DELETE, so a backlog can consume each replica's four origin slots and 15-second cleanup budget repeating work instead of advancing to other artifacts. Make the claim conditional on the row still being due and matching the observed attempt, ideally with an UPDATE ... WHERE ... RETURNING fence.

AGENTS.md reference: AGENTS.md:L12-L14

Useful? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

v1.0 Silo v1 scope - auto-adds to the Silo v1 project

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant