Skip to content

perf(apiv2): keep sendfile on v2 playback and theme audio routes - #2548

Merged
Quick104 merged 1 commit into
Silo-Server:mainfrom
blurbery:perf/apiv2-delivery-sendfile
Oct 17, 2026
Merged

Quick104 merged 1 commit into
Silo-Server:mainfrom
blurbery:perf/apiv2-delivery-sendfile

Conversation

@blurbery

@blurbery blurbery commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Related issue: N/A
Validation tasks: changes #1252 C3; changes Silo-Server/silo-apple#337 C3

Media files served through the v2 playback routes never use sendfile. Each one is copied through a 32 KB buffer in user space instead. That covers web video playback, since the web player starts every play through /api/v2/playback/start and the plan points local media at /api/v2/stream/{session_id}, and the native clients' v2 playback as well. This change lets direct play, local HLS segments and original theme audio reach the connection's ReadFrom again.

internal/httpstream/readfrom.go explains why: io.Copy finds io.ReaderFrom only by direct type assertion, never through Unwrap, so one wrapper without ReadFrom turns zero-copy off for every writer below it. playbackDeliveryWriter, directDownloadWriter and the streamResponseWriter they share have Write, WriteHeader, FlushError and Unwrap, but no ReadFrom. When direct play calls http.ServeContent, the ReadFrom that RollingDeadlineWriter and the stream telemetry writer pass down lands on playbackDeliveryWriter, and httpstream.ForwardReadFrom falls back to io.Copy. #1647 fixed the same gap in statusRecorder and the managed download routes; these writers were missed.

Both validation cases above passed direct play, remux and HLS in rehearsal runs. The change affects how bytes are copied, not which bytes or headers are sent, so they should still pass.

Approach

  • streamResponseWriter.ReadFrom forwards through httpstream.ForwardReadFrom once a success status is committed. http.ServeContent writes its status before it copies, so every file it serves on these routes takes the fast path.
  • A copy that starts before any status still goes through Write, which commits 200 only on the first byte. A source that fails before yielding anything still gets its v2 problem response, and one that fails after bytes still ends the stream instead of appending JSON. No handler on these routes reaches ReadFrom before setting a status today; this keeps the writer's rule the same whichever way bytes arrive. After a rejected status, copied bytes are still discarded.
  • playbackDeliveryWriter and directDownloadWriter hand ReadFrom to that writer, as they already do for Write. directDownloadWriter serves the direct download and theme song routes.

Still copied in user space after this change:

  • Original files from /api/v2/direct-download. The download service wraps the file and the writer to catch read errors and short transfers (fix(downloads): keep interrupted direct downloads from appending a JSON error #2235), so sendfile can't see the file whatever the v2 writer does. Fixing that is a separate change in internal/downloads.
  • The manifest and subtitle routes, because the v1 router's compression wrappers sit below statusRecorder there and have no ReadFrom. A subtitle cache hit now reaches those wrappers instead of stopping at the v2 writer. These bodies are small text.

jellycompat and /api/v1 don't use these writers.

Validation

Tested commit: f6436f4, on main at 9a2b950.

  • Go: the internal/apiv2 tests pass, except TestAdminResourceCapabilitiesAndScope, which needs Linux cgroups and fails the same way on main on macOS. go vet and gofmt are clean on the package.
    • New tests serve a file on the v2 stream route through the real direct-play handler (a full response and a byte range), and original theme audio through themesongs.Serve. They check that every byte reaches the connection's ReadFrom from the *os.File, under at most one io.LimitedReader, which is what sendfile needs. On main no byte does, and both tests fail.
    • Two more tests copy before any status: a source that fails at once still gets a problem response, and one that fails after bytes aborts without appending JSON. They pass on main too and guard the new path.
  • Not covered: these are handler-level tests through the v2 router. They don't mount the v1 router's middleware over a real socket, which docs/architecture/streaming-write-deadline.md names as the conformance check, and I didn't trace sendfile calls with strace.
  • Not run locally: make lint-changed, make test-go and the contract checks. My machine blocks whole-repo runs; CI runs them. No web files changed.

Benchmarks

A 256 MiB file served on the v2 stream route by playback.ServeDirectPlay, through apiv2.NewHandler with its middleware, over loopback TCP to a client in the same process. main at 9a2b950 against this branch, five runs of testing.Benchmark each, macOS on Apple silicon, Go 1.27.1. Each cell is the lowest to highest of the five runs.

Per 256 MiB request main This branch
Throughput 6.19 to 6.43 GB/s 8.29 to 8.91 GB/s
Time 41.8 to 43.3 ms 30.1 to 32.4 ms
System CPU per GiB 267 to 273 ms 222 to 225 ms
User CPU per GiB 41 to 42 ms 36 to 37 ms
Bytes allocated 49.1 to 52.3 KB 23.7 to 27.1 KB
Allocations 187 to 197 508 to 515

The allocation count rises by about five for each 4 MiB slice RollingDeadlineWriter hands down; the bytes allocated still halve.

Limits:

  • CPU is for the whole process, so it includes the client reading the body. The client does the same work in both runs.
  • It runs the v2 handler alone, without the v1 router middleware or stream telemetry.
  • I haven't measured on Linux, where most servers run.
  • sendfile only applies on a plain HTTP listener, for example behind a reverse proxy. On Silo's built-in TLS listener net/http copies in user space either way.
Benchmark source (a throwaway test in internal/apiv2, not committed)
package apiv2

import (
	"io"
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"
	"syscall"
	"testing"

	"github.com/Silo-Server/silo-server/internal/playback"
)

// TestPlaybackDeliveryFileBenchmark serves a 256 MiB file through the v2
// stream route over a real loopback TCP connection and reports process CPU per
// GiB, five times. Set SILO_SENDFILE_BENCH=1 to run it.
func TestPlaybackDeliveryFileBenchmark(t *testing.T) {
	if os.Getenv("SILO_SENDFILE_BENCH") == "" {
		t.Skip("set SILO_SENDFILE_BENCH=1")
	}
	const size = 256 << 20
	path := filepath.Join(t.TempDir(), "fixture.mp4")
	f, err := os.Create(path)
	if err != nil {
		t.Fatal(err)
	}
	chunk := make([]byte, 1<<20)
	for i := range chunk {
		chunk[i] = byte(i)
	}
	for written := 0; written < size; written += len(chunk) {
		if _, err := f.Write(chunk); err != nil {
			t.Fatal(err)
		}
	}
	_ = f.Close()

	deps, _ := catalogDeps(t)
	deps.PlaybackMedia = &PlaybackMediaHandlers{Original: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		_ = playback.ServeDirectPlay(w, r, path)
	})}
	h := NewHandler(deps)
	srv := httptest.NewServer(h)
	defer srv.Close()
	client := srv.Client()
	url := srv.URL + Prefix + "/stream/" + deliveryTestSession + "?st=opaque"
	headers := viewerHeaders()

	bench := func(b *testing.B) {
		var before, after syscall.Rusage
		b.SetBytes(size)
		b.ReportAllocs()
		b.ResetTimer()
		_ = syscall.Getrusage(syscall.RUSAGE_SELF, &before)
		for b.Loop() {
			req, _ := http.NewRequest(http.MethodGet, url, nil)
			for k, v := range headers {
				req.Header.Set(k, v)
			}
			resp, err := client.Do(req)
			if err != nil {
				b.Fatal(err)
			}
			n, err := io.Copy(io.Discard, resp.Body)
			_ = resp.Body.Close()
			if err != nil || n != size || resp.StatusCode != 200 {
				b.Fatalf("status %d, %d bytes, %v", resp.StatusCode, n, err)
			}
		}
		_ = syscall.Getrusage(syscall.RUSAGE_SELF, &after)
		b.StopTimer()
		gib := float64(b.N) * size / (1 << 30)
		cpu := func(tv syscall.Timeval) float64 { return float64(tv.Sec) + float64(tv.Usec)/1e6 }
		b.ReportMetric((cpu(after.Utime)-cpu(before.Utime))*1000/gib, "user-ms/GiB")
		b.ReportMetric((cpu(after.Stime)-cpu(before.Stime))*1000/gib, "sys-ms/GiB")
	}
	for range 5 {
		res := testing.Benchmark(bench)
		t.Logf("%s\t%s\tuser-ms/GiB=%.0f\tsys-ms/GiB=%.0f", res.String(), res.MemString(), res.Extra["user-ms/GiB"], res.Extra["sys-ms/GiB"])
	}
}

Evidence

Evidence: https://evidence.siloserver.org/r/silo-server/pr-2548/

Nothing visible changes: responses keep the same bytes and headers. The page has the test output on main and on this branch (no file bytes reach ReadFrom on main, all of them do here) and the raw benchmark runs.

Risks

None identified. A copy that fails partway through a committed response now fails inside the wrapped writer's ReadFrom instead of Write, and the stream ends the same way.

Checklist

  • I read and can explain the complete diff.
  • This pull request addresses one concern.
  • The Evidence section shows every change a user can see, or says there is none.

AI Disclosure

  • Harness: Claude Code (Claude desktop app)
  • Tool(s): Claude Code, Claude Code subagents for tracing the writer chain and for review, GitHub CLI
  • Model(s): claude-opus-5-5
  • Involvement: AI-assisted with Claude Opus. I directed the task and designed the work.
  • Adversarial review: a separate Claude Code subagent reviewed the diff and ran probe tests against the old and new code. It checked the status commitment rules (304, HEAD, 416, multi-range, a rejected status, repeated copies), the writers below for early commits, byte accounting, other callers and the tests. It found no correctness problem. It did find that original direct downloads still can't use sendfile because of the download service's own wrappers, and that the first version's direct download test bypassed that service. I replaced that test with one through the real theme audio path, made both tests check that the file reaches ReadFrom, and narrowed this description. It also asked for a clearer code comment, which is in.

Note

Keep zero-copy sendfile on v2 playback and theme audio routes

Adds ReadFrom methods so io.Copy can use the underlying transport's reader-from path when serving file-backed media.

  • directDownloadWriter.ReadFrom and playbackDeliveryWriter.ReadFrom in direct_download.go and playback_delivery.go delegate copying to the wrapped transport.
  • streamResponseWriter.ReadFrom in stream_response_writer.go routes pre-status and rejected copies through the write-only adapter, while committed responses forward to the wrapped writer's ReadFrom, preserving first-byte commitment and failure handling.
  • Tests add file-aware byte accounting in observe_test.go and integration tests for zero-copy playback delivery, copy-failure paths, and theme-song audio in playback_delivery_test.go and theme_songs_test.go.

Macroscope summarized f6436f4.

io.Copy finds io.ReaderFrom only by direct type assertion, and the v2
playback delivery and direct download writers, and the streamResponseWriter
they share, had no ReadFrom. Files served through them, such as direct
play, local HLS segments and original theme audio, fell back to a 32 KB
user-space copy instead of the connection's sendfile path.

streamResponseWriter now forwards ReadFrom once a success status is
committed, as http.ServeContent does before copying. A copy that starts
before any status still goes through Write, so a source that fails before
its first byte still gets a problem response, and one that fails after
bytes still aborts.
@silo-triage silo-triage Bot added the size/M 50–199 added + deleted lines (all files); change volume, not priority. label Oct 15, 2026
@silo-kody

silo-kody Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@silo-triage silo-triage Bot added api-v2 API v2 / Huma migration program (epic #135); long-running, stacked by phase bug Something isn't working go Pull requests that update go code priority: P2 Limited scope, workaround exists, or polish triaged High-confidence review completed; does not mean fixed, validated, or accepted for release. labels Oct 15, 2026
@coderabbitai

coderabbitai Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 30d6e822-9ce6-4a8e-adaa-f829b1d9e8a2
📥 Commits

Reviewing files that changed from the base of the PR and between 9a2b950 and f6436f4.

📒 Files selected for processing: 6
  • internal/apiv2/direct_download.go
  • internal/apiv2/observe_test.go
  • internal/apiv2/playback_delivery.go
  • internal/apiv2/playback_delivery_test.go
  • internal/apiv2/stream_response_writer.go
  • internal/apiv2/theme_songs_test.go

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 0 remain after this review.

📝 Walkthrough

V2 response writers now implement io.ReaderFrom and delegate reader copies through their transport. Tests cover file-backed full and ranged responses, status handling, and copy failures before and after bytes are written.

Changes: V2 response copying

Layer / File(s) Summary
Add ReadFrom delegation
internal/apiv2/direct_download.go, internal/apiv2/playback_delivery.go, internal/apiv2/stream_response_writer.go
The direct-download and playback writers delegate ReadFrom to their transport. streamResponseWriter routes copies through Write when the response status is unset or rejected, and otherwise forwards to the wrapped writer when supported.
Verify file copies and copy failures
internal/apiv2/observe_test.go, internal/apiv2/playback_delivery_test.go, internal/apiv2/theme_songs_test.go
Tests track bytes copied from files, including files wrapped by a limited reader. Delivery tests cover full and ranged responses, plus copy failures before and after writing bytes. A theme-song test checks file-backed audio delivery.

Priority: ⬇️ Low

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

Change: Bug fix

Suggested reviewers: quick104

Merge Risk: ⚪ Minimal · up to f6436

The changed playback and theme-audio paths retain their response handling while allowing eligible file copies to use ReadFrom. No merge-blocking issue was identified.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 37.50% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 8 functions across 6 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed 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.
Title check Passed The title clearly and concisely describes the main change: preserving sendfile for v2 playback and theme audio routes.
Description check Passed The description directly explains the problem, implementation, validation, benchmarks, limitations, and risks for the changeset.
  • Fix all pre-merge checks with AI
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

@Quick104
Quick104 merged commit 707f1ae into Silo-Server:main Oct 17, 2026
16 checks passed
@blurbery
blurbery deleted the perf/apiv2-delivery-sendfile branch November 6, 2026 00:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

api-v2 API v2 / Huma migration program (epic #135); long-running, stacked by phase bug Something isn't working go Pull requests that update go code priority: P2 Limited scope, workaround exists, or polish size/M 50–199 added + deleted lines (all files); change volume, not priority. triaged High-confidence review completed; does not mean fixed, validated, or accepted for release.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants