Skip to content

perf(playback): sync sessions on progress only when pause state flips - #1364

Merged
Quick104 merged 1 commit into
mainfrom
perf/playback-heartbeat-sync
Sep 24, 2026
Merged

Quick104 merged 1 commit into
mainfrom
perf/playback-heartbeat-sync

Conversation

@Quick104

Copy link
Copy Markdown
Contributor

Problem

Related issue: N/A
Validation tasks: changes #1207 C1 (the admin Active sessions position now updates on the reconcile tick, not on each client heartbeat); reaches #1206 C1 and #1208 C1, where pause and resume still reach the admin view at once. None of these cases has a recorded result yet.

Each progress sample on /api/v1 and /api/v2 called the session syncer (SyncNow) when the API server held the live session. A sync reconciles every live session on that node, not only the one that reported. It runs one transaction of N+5 statements for N sessions. The reconciler treats a position change as a change, so each sync also sends sessions.replaced to every connected admin client and publishes playback_sessions_changed. That event drops the admin stats, activity, leaderboard and timeseries caches on every replica. The plugin event dispatcher also receives both events on every replica. For each one it queries the enabled plugin installations and their capabilities before forwarding the event to matching plugin event consumers.

The web player and the Android client report progress every 10 seconds. A node with 20 streams therefore rewrites all 20 shared rows about twice a second and keeps the admin caches cold. Operators pay that cost in database load, and admins see their dashboards refetch continuously. Jellyfin-compatible progress reports already skip SyncNow, so native clients paid a cost that compat clients did not.

Approach

A progress sample now calls SyncNow only when it flips the pause state (wasPaused != IsPaused). Position-only samples still update the in-memory session, the user store and watch-provider scrobbles as before. The shared admin row picks up the new position on the next periodic reconcile tick (every 15 seconds), which already runs on every node.

Start (v3_start), replan (v3_replan), stop and abort sync from their own call sites and are unchanged. The new tests check that stop still syncs on both API versions.

Alternatives considered:

  • Ignoring position in the reconciler's change detection. That would cut the admin events but not the per-heartbeat transaction, and it changes what the tick publishes. It is out of scope here.
  • Syncing only the reporting session's row. That needs a second reconcile path next to the node snapshot, and a position the tick delivers within 15 seconds does not justify one.

Audiobookshelf-compatible progress (beta) also syncs on each update. This PR leaves it alone.

Maintainer PR #1078 edits the same two files, in the progress side-effect lock and the handler struct fields. This diff changes one line in writeProgressSideEffectsV2 and one in HandleUpdateProgress, and adds a small helper next to syncSessionsNow. It does not touch the lock code. git merge-tree auto-merges these hunks with #1078 in both files. #1078 already conflicts with main in finalizeStopV2's stop-lease loop and in internal/transcodenode/server.go; this PR does not change either conflict.

Before and after

Metric Before After How measured
Syncs for 100 position-only samples, v2 100 0 TestApplyProgressV2SyncsSessionsOnlyOnPauseFlip, counting syncer
Syncs for 100 position-only samples, v1 100 0 TestHandleUpdateProgressSyncsSessionsOnlyOnPauseFlip, counting syncer
Syncs for one pause flip, v1 and v2 1 1 same tests
Syncs for a repeated paused sample, v1 and v2 1 0 same tests
Syncs for stop, v1 and v2 1 1 same tests
Reconciler statements per position-only v1 POST, 1 live session 6 0 temporary Postgres test with a pgx query tracer and a real worker.Reconciler as the syncer (not committed)
Reconciler statements per position-only v1 POST, 20 live sessions 25 0 same
playback_sessions_changed publishes per 100 position-only POSTs 100 0 same, counting event bus
Reconciler statements for one pause-flip POST, 1 and 20 sessions 6 and 25 6 and 25 same

The statement counts cover only the reconciler. The handler under test had no user store, and the per-sample user-store write is unchanged. For scale, as an estimate: 20 streams reporting every 10 seconds went from about 52 reconciler statements a second (two heartbeat syncs plus the tick) to one 25-statement sync per 15-second tick, about 1.7 a second.

Validation

All checks below ran on the branch rebased onto current main.

  • go build ./..., gofmt -l . (no output) and go vet ./...: pass.
  • make lint-changed: 0 issues.
  • GOFLAGS=-p=6 make test-go (without SILO_TEST_DATABASE_URL): pass, 159 packages ok.
  • With SILO_TEST_DATABASE_URL set to a freshly migrated database, go test ./internal/api/handlers/ ./internal/worker/ ./internal/apiv2/: worker and apiv2 pass. handlers fails only TestAdminSubtitleListPageDB and TestCatalogTransferPersistsJobsAndSignedLink, and both fail the same way on current main.
  • make verify-settings-bindings-all verify-playback-fixtures verify-route-inventory verify-migration-ledger verify-scenario-catalogs verify-offline-routes verify-apiv2-openapi verify-apiv2-contract verify-apiv2-fixtures verify-local-paths: pass.
  • go test -count=1 -run '^TestCommittedArtifactMatchesRouter$' ./internal/apiv2/: pass.
  • Both new tests fail on current main with 100 syncs where 0 are expected. On main, a copy of the tests that logs each step shows one sync each for the pause flip, the repeated paused sample, the resume and the stop, as in the Before column. The tests pass on this branch, including under -race -count=30.
  • A throwaway Postgres test with a query tracer (not committed) counted the statements of one SyncNow on a real worker.Reconciler: 6 with 1 live session and 25 with 20, matching the pause-flip row.
  • make test-web, the web build and make migrate-validate do not apply: the branch changes no files under web/ or migrations/.

Risks

  • The admin Active sessions view now moves a playing session's position on the reconcile tick, so it can trail the player by up to 15 seconds more than before. Pause, resume, start, stop and replan still show at once.
  • The household-manager session list (v1 GET /api/v1/profiles/household/sessions and v2 listHouseholdSessions) reads the same shared row. Its position_seconds now also updates on the reconcile tick, and its is_paused still updates at once. The first-party web household panel shows only Playing or Paused, so it looks the same. A third-party client that shows position from this endpoint will see it move every 15 seconds.
  • Plugins subscribed to playback_sessions_changed or sessions.replaced now receive them on the tick and on start, stop, replan and pause changes, not on every heartbeat. No first-party plugin or the plugin SDK consumes these events.
  • The v1 handler reads the previous pause state without a per-session lock. If two v1 samples for one session race and flip pause twice, the second flip can skip its sync. The next tick corrects the shared row within 15 seconds. The v2 path reads and updates the live session under its per-session lock and does not have this race.
  • Stale-row cleanup keys on last_sync_at, with a 45-second grace for playing sessions. The 15-second tick refreshes it, so dropping heartbeat syncs does not expire live rows.

Checklist

  • I read and can explain the complete diff.
  • This pull request addresses one concern.

AI Disclosure

  • Harness: Claude Code, running in T3 Code
  • Tool(s): Claude Code built-in tools (shell, file read/edit, Workflow subagents), GitHub CLI (gh)
  • Model(s): claude-opus-5-5[1m] for the main session and all subagents
  • Involvement: Fully AI-generated; maintainer review pending
  • Adversarial review: a separate reviewer subagent (claude-opus-5-5) reviewed the full diff and approved it with no blocking or major findings. It re-ran every before/after number in clean worktrees at the base and branch commits, using its own counting-syncer test and a throwaway Postgres database with a query tracer and a real reconciler, and all numbers matched. It also checked for regressions: the other sync call sites, tick coverage and stale-row cleanup, admin pause and resume, Jellyfin-compatible progress, v2 lock ordering, the wire contract, merges with main and fix(playback): retain progress side effect lock identity #1078, and the validation tasks. It raised five documentation items and no code issues, and all five are fixed: the Risks section now covers the household-manager session list, which reads the same shared row; Problem and Risks now cover the plugin event dispatcher, which receives the same events; the fix(playback): retain progress side effect lock identity #1078 note now states only what git merge-tree shows; this review field replaces a placeholder; and the commit message now gives the 10-second client cadence instead of "every few seconds".

🤖 Generated with Claude Code

Every v1 and v2 progress sample called SyncNow, which reconciles the whole
node's live-session snapshot: one transaction of N+5 statements for N local
sessions, then a sessions.replaced push to every admin socket and a
playback-sessions invalidation on every replica. With the web and Android
clients reporting progress every 10 seconds, the shared admin view was
rewritten and its caches dropped once per heartbeat per stream.

Position does not need that. The periodic reconcile tick already carries
it, and jellycompat progress never triggered a sync. A progress sample now
syncs only when it flips the pause state, so the admin view still shows
pause and resume at once. Start, replan, stop and abort keep syncing from
their own call sites.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

@greptile-apps greptile-apps 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.

Quick104 has reached the 50-credit limit for trial accounts. To continue receiving code reviews, upgrade your plan.

@coderabbitai

coderabbitai Bot commented Sep 24, 2026

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

Next included review available in 1 minute.

Check out review usage here.

View limit details

Limit details: You’ve used all 2 included reviews currently available.

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Advanced

Run ID: f274d811-f862-4cff-b8aa-2e54fc5a40a9

📥 Commits

Reviewing files that changed from the base of the PR and between d4e35ba and ce2de7a.

📒 Files selected for processing (3)
  • internal/api/handlers/playback.go
  • internal/api/handlers/playback_progress_sync_test.go
  • internal/api/handlers/playback_service.go

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.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 24, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-24T03:58:54.714928Z ce2de7a PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@Quick104
Quick104 merged commit df0e9d9 into main Sep 24, 2026
15 of 16 checks passed
@Quick104
Quick104 deleted the perf/playback-heartbeat-sync branch September 24, 2026 14:15
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