Skip to content

fix(audiobooks): send offline listening on downloaded books to the server - #961

Merged
Quick104 merged 8 commits into
mainfrom
fix/957-offline-audiobook-progress-sync
Nov 16, 2026
Merged

Quick104 merged 8 commits into
mainfrom
fix/957-offline-audiobook-progress-sync

Conversation

@Quick104

@Quick104 Quick104 commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Problem

On Android, listening to a downloaded audiobook never moved the book's position on the server, offline or online. A downloaded book plays its local file with no server session, and the player saved its position on the device only: it wrote through the unscoped recordPosition, which never queues anything. Continue Listening and other devices kept the position from the last streamed session.

#847 added the queue this needs for downloaded video (SET_POSITION v2 through POST /api/v2/sync/progress with updated_at); the audiobook player never used it. The ebookAuthorities early return named in #957 came from 48fa359, which held legacy position rows that had no login authority; #847 replaced it with scoped v2 ops, so it no longer blocks this.

Solution

This follows Silo-Server/silo-apple#1192's rules.

  • When the downloaded file is the whole book, each position goes through the app-owned FinalPlaybackPositionWriter with the time it was sampled, about every 10 s of listening and on pause, seek and close. The server merges by updated_at, newest first, so an earlier position played later still wins. isWholeBookFile must prove the file is the whole book (one logical part, and close to the server's total); a part of a multi-part book stays on the device, as before.
  • A position still waiting to reach the server beats the server's resume point, online and offline. The player reads detail from the server only, so a cached copy is never taken as the server's answer, and reads it again if the server took this device's queued listening while it loaded (Apple's onlineContext).
  • When the server accepts a position, the device keeps it, marked sent (user_item_state.serverUpdatedAtMs, which nothing wrote before). Online the server's answer stands over it, per [bug] Android keeps download progress on the device only, and it overrides the server's watched state #846; offline it is the resume point, ahead of the cached server answer. A new sample clears the mark. Before, the accepted copy was deleted and offline resume fell back to the cached detail, which can be far behind.
  • A send that may have arrived (a timeout, an unreadable answer, a gateway error; RequestMutationFailure.isUncertain) is marked the same way. It is still sent again, as fix(progress): send download progress to the server and stop stale local resume #847 does, but at start the server's answer stands. A refusal before sending (sign-in unavailable, cleartext not allowed, a failed TLS handshake) or a failed connection stays unsent. This also applies to downloaded video: cards, detail and the video player's online resume skip marked positions, and the video player still uses them offline.
  • When the reachability monitor finds the server (foreground start, or recovery while the network stayed up) and download progress is queued, the progress leaves its backoff and a separate drain runs right away instead of waiting for a retry in WorkManager's backoff. A process-wide lock keeps drains one at a time, so nothing running is cancelled, and a request made while a drain finishes still gets its own drain.
  • Offline, the audiobook player now starts at a requested position (a chapter or bookmark), as the online path does; it used to start at the saved resume point.

Closes #957
Related issue: #846
Validation tasks: unavailable (this run's GitHub token can't read the validation board)
Other clients: Apple N/A (Silo-Server/silo-apple#1192 is the reference for these rules); Roku N/A (audiobooks and offline downloads are deferred in docs/spec.md); Web N/A (no offline downloads)

Validation

Reproduced on a dev sandbox (server main) with a phone emulator, using a generated single-file audiobook in a new audiobook library, then verified on the fix with the same data:

  • Before: listening offline to 10:16 left the position on the device with nothing queued; 48 s after reconnecting the server had no progress for the book.
  • After: offline listening was queued with its sample time and reached the server about 3 to 10 s after reconnecting. Offline again after a sync, the book resumed at the synced spot. A rewind made offline replaced the server's higher, older position.
  • Another device setting the server to 5:00 won online over the device's marked 10:39.
  • With the server down and the network up, sends failed with "connection refused" and stayed unsent. When the server came back, the queued position arrived about 4 to 9 s later, while its retry was still about 112 to 115 s away. Re-checked on a fresh sandbox after the drain became separate work (d03a960): the drain-now worker sent it and the server stored it with its offline sample time.
  • Offline, tapping Chapter Two started at 10:00; main started at 0:00.
  • SyncEngineTest.downloadProgressIsSentWithItsEventTimeAndThenStopsOverridingTheServer fails on main ("kept as the offline resume point expected:<646.5> but was:<0.0>") and passes here. The other new tests (sent and uncertain marks, never-connected sends, the whole-book check) use new parameters or functions, so they don't build on main.
  • testDebugUnitTest (all modules), lintDebug (android-shared, phone, TV), lintVitalRelease and assembleDebug (phone, TV) pass. One unrelated CatalogLetterIndexViewModelTest failure appeared once in a full run; it passes alone and in later full runs, here and on main. The supply-chain scripts need Ruby, which the test host lacks; CI runs them.
  • Devices: the phone emulator covers the phone. Tablet and foldable run the same player and repository with no form-factor branch. Android TV uses the same shared audiobook view model and DI change; no TV run was made. No multi-part book was available on the sandbox; the whole-book check has a unit test, and multi-part books keep the existing part-local suppression.

Evidence: https://evidence.siloserver.org/r/silo-android/957-offline-audiobook-sync/

Risks

Follow-ups

Adversarial review

Plan round 1: gpt-6.1-sol (xhigh) attacked the plan (adopted: positive whole-book check, keep the accepted position for offline resume; the unanswered-send rule and the reachability drain went to the maintainer, who folded them in); claude-opus-5-5 (high) cut it (dropped a redundant final write in stopPlaybackSession). Plan round 2 for the follow-ups: Sol (fresh detail reads, offline video fallback, pre-send refusals, a re-read when the server accepts during load, no RUNNING shortcut without a wake flag) and Opus (reuse RequestMutationFailure.isUncertain, drop crash-stranded marking, don't cancel a running drain). Code review at high, twice (three finders each): fixed the recorded file id, a 10 s queue throttle, the offline chapter start, the same-file mark predicate, TLS and cleartext refusals, a generation recheck, a port default, gating and ordering of the reachability drain; removed a first reachability hook that WorkManager's KEEP policy made ineffective. Simplify ran on each round. Bot review (Codex, Kody) on b7694d8: fixed offline resume preferring a stale cached position, a sent-mark failure turning an op terminal, the video re-read, and unindexed multi-file books (49afc0a); the unanswered-send rule and the worker wake window are answered in their threads; #963 filed. Background review (gpt-6.1-sol) on b7694d8 stopped before posting because the head moved; its findings were the offline cached-position preference and unindexed multi-file books (both fixed in 49afc0a) and a race where REPLACE could cancel a starting drain (fixed in d03a960 by making the reachability drain separate work behind a lock). Later bot comments: Kody (re-check local progress after the video re-read, indexed alternates; 2755db8) and CodeRabbit (decide the audiobook re-read from the final local read; 932a6dd). Background review round 2 (gpt-6.1-sol, reviewed 932a6dd): one finding, progress written during the audiobook detail re-read was ignored; fixed in a101ed3, which also reads local progress again after that request and keeps a main-chain retry for work a drain-now worker leaves (both also raised by Kody). Open for the maintainer: Kody on excluding unanswered sends at start (the chosen rule), and CodeRabbit on the video player keeping the earlier sample when its re-read fails (deliberate, as in Apple's onlineContext).

AI disclosure

  • Harness: Claude Code (in T3 Code)
  • Tool(s): Claude Code, GitHub CLI, agent-device on a local Android phone emulator, a Silo dev sandbox, Codex (plan review)
  • Model(s): claude-opus-5-5 (wrote the code), gpt-6.1-sol and claude-opus-5-5 (plan and code review)
  • Involvement: AI-generated, verified live on an Android phone emulator by the agent. Not yet reviewed by a person.

🤖 Generated with Claude Code

Note

Send offline listening progress on downloaded audiobooks to the server

  • Downloaded whole-book audiobook playback now queues progress samples through FinalPlaybackPositionWriter. Periodic saves are throttled to submit only when the position changes by at least a 10-second interval.
  • Eligibility is decided by the new isWholeBookFile predicate in AudiobookTimeline.kt, which requires the file to cover at least 90% of the server total (or be a single/same-part audio candidate).
  • SyncEngine retains accepted progress locally with a serverUpdatedAtMs sent marker instead of clearing it. Uncertain writes that may have reached the server are marked sent while the outbox operation stays queued; connection-refused and similar pre-send failures are not marked.
  • Local progress reads gain an includeSent option across UserItemStatePort, so offline resume uses sent-inclusive samples and online reads exclude them. On server reachability, pending download progress is made due and drained immediately via enqueueNow on SyncWorker.
  • Risk: localPosition, localPositionForContent, localPlaybackProgress, and localPlaybackProgressForContent in UserItemStatePort.kt changed signatures; out-of-tree implementations must add the includeSent argument.

Macroscope summarized a101ed3.

Quick104 and others added 3 commits November 16, 2026 00:49
…rver

A downloaded audiobook plays its local file with no server session, and the
player saved its position on the device only, so listening done offline (or
online from the download) never reached the server.

Downloaded books whose file is the whole book now queue each position with
the time it was sampled, through the outbox #847 added for downloaded video,
and it goes to POST /api/v2/sync/progress once the server can be reached.
Unsent listening wins at start. A part of a multi-part book stays local.
The accepted position stays on the device for offline resume.

Refs #957

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ain when the server returns

The maintainer's three follow-ups for #957, from the Apple rules:

- A position the server accepted is kept on the device, marked sent.
  Online the server's answer stands over it; offline it is the resume
  point. A new sample clears the mark.
- A send that may have arrived without an answer (a timeout, an unreadable
  reply, a gateway error) is marked the same way: it is still sent again,
  but no longer beats the server's position at start. A refusal before
  sending or a failed connection stays unsent. Video resume reads marked
  positions only when it has no live server answer.
- When the server becomes reachable (foreground start or recovery), queued
  download progress leaves its backoff and a drain replaces a retry waiting
  in WorkManager's backoff, without cancelling a drain already running.

The audiobook player reads detail from the server only, so a cached copy is
never taken as the server's answer, and reads it again when the server took
this device's queued listening while it loaded.

Refs #957

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…drain

- Offline, the audiobook player now starts at a requested position (a
  chapter, a bookmark), as the online path does. Reading detail live only
  sent every offline open there, which made the old gap common.
- A mark on the op's own file needs that file's row to still hold the
  op's sample, so a newer sample after a clock correction stays unsent.
- A TLS handshake failure or a platform cleartext block counts as never
  sent.
- The audiobook load rechecks its generation after re-reading detail.
- localPositionForContent leaves sent positions out by default, like the
  other unsent reads.
- The reachability drain runs only when download progress is queued, and
  before the config refresh, which can fail.

Refs #957

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-16T03:56:13.664681Z a101ed3 New commits
🔒 Security Review ✅ Completed 2026-11-16T04:02:24.964649Z a101ed3 New commits
ℹ️ 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.

@silo-triage silo-triage Bot added the size/L 200–499 added + deleted lines (all files); change volume, not priority. label Nov 16, 2026
@silo-kody

silo-kody Bot commented Nov 16, 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 ❌

@coderabbitai

coderabbitai Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

Explain Change →

Walkthrough

Downloaded whole-book audiobook playback now records progress for synchronization. The player distinguishes unsent samples from samples marked sent when resolving resume positions. When the server becomes reachable, queued progress can be made due and sent.

Changes: Offline audiobook progress

Layer / File(s) Summary
Progress state and lookup
shared/src/commonMain/kotlin/org/siloserver/silo/repository/port/UserItemStatePort.kt, android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/db/dao/UserItemStateDao.kt, android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/repository/RoomUserItemStateRepository.kt, android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/data/repository/RoomUserItemStateRepositoryTest.kt, shared/src/commonTest/kotlin/org/siloserver/silo/viewmodel/HomeScreenV2Test.kt, androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/detail/TvNextUpSelectionHandoffTest.kt
Local progress lookup methods accept includeSent, which defaults to false. The repository clears the sent timestamp for new samples, and the DAO can mark samples sent. Tests and test doubles reflect these changes.
Whole-book download playback and resume
shared/src/commonMain/kotlin/org/siloserver/silo/audiobook/AudiobookTimeline.kt, shared/src/commonTest/kotlin/org/siloserver/silo/audiobook/AudiobookTimelineTest.kt, android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/AudiobookPlayerViewModel.kt, androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerViewModel.kt, androidApp/src/androidMain/kotlin/org/siloserver/silo/android/di/AndroidModule.kt, androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/di/AndroidTvModule.kt
The timeline identifies whole-book files. The player resolves resume positions from local and server progress and submits qualifying positions for download playback, with periodic submissions throttled to changes of at least 10 seconds. Android and TV bindings provide the playback-position writer.
Progress sync and connectivity wake-up
android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/db/dao/DirtyOperationDao.kt, android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/sync/SyncEngine.kt, android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/sync/SyncWorker.kt, android-shared/src/androidMain/kotlin/org/siloserver/silo/common/network/ServerReachabilityMonitor.kt, android-shared/src/androidMain/kotlin/org/siloserver/silo/common/di/PlayerInfraModule.kt, android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/data/sync/SyncEngineTest.kt
The sync engine records accepted samples as sent and preserves samples after uncertain sends that may have reached the server. On reachability, queued operations can be made due and immediate sync can be requested. The worker repeats a drain when another request arrives during execution. Tests cover accepted, timed-out, and connection-refused sends.

Estimated code review effort: 4 (Complex) | ~45 minutes

Change: Bug fix · Severity of issue fixed: Medium

Sequence Diagram(s)

sequenceDiagram
  participant ServerReachabilityMonitor
  participant PlayerInfraModule
  participant DirtyOperationDao
  participant SyncWorker
  participant SyncEngine
  participant Server
  ServerReachabilityMonitor->>PlayerInfraModule: onServerReachable callback
  PlayerInfraModule->>DirtyOperationDao: make queued progress due
  PlayerInfraModule->>SyncWorker: enqueueNow when rows were updated
  SyncWorker->>SyncEngine: drainOnce
  SyncEngine->>Server: send download progress
Loading

Possibly related issues

  • Issue 846: The PR covers offline audiobook progress synchronization, but does not cover the issue’s video overlay behavior.
  • Issue 349: The PR changes whole-book download progress and resume handling related to the tracker’s cross-device and exact-second cases; it does not claim to complete the tracker.
  • Issue 350: The PR changes shared playback behavior related to the tracker’s cross-device and exact-second cases; no TV test run is reported.

Suggested reviewers: rxwatcher, rhainland

Merge Risk: Moderate · up to b7694

Offline audiobook progress now syncs, but in narrow timing windows resume can pick a stale or older position instead of the latest server or local one. A worker run can also skip a retry for earlier-scope work. These are limited to specific interleavings and delay or misplace progress; they do not lose data. Fix the resume races before merging, or accept them explicitly.

Security architecture risk: Low · up to b7694

The reconnect path can interrupt unrelated favorite or watchlist changes if background synchronization starts during its running-state check. Safe cancellation cleanup limits the impact, but those actions may unnecessarily require reconciliation. The inspected progress-writing paths retain account and profile controls.

Retained concerns

  • Low · reliability · inferred: The reconnect wake-up does not atomically preserve starting or running synchronization. enqueueNow can observe no RUNNING work, then issue REPLACE after the existing worker has started. Because that worker also dispatches favorite/watchlist mutations, an audiobook-progress wake-up can cancel unrelated mutations and move them into reconciliation. Exact-claim cancellation cleanup prevents unsafe automatic replay, but does not preserve the intended isolation between progress wake-ups and unrelated in-flight actions.
Security review details

Security Blast Radius

  • observed — Each progress replay carries one content item's listening state under a captured profile. Queue selection and local sent-state updates include server, account, and profile identifiers. The reconnect wake-up changes scheduling across pending progress rows, but dispatch still selects a captured account scope.

Trust Boundaries and Controls

  • observed — Local-media resolution uses server/account/profile-scoped metadata and storage. Before recording a captured playback sample, the repository checks server, profile, temporary-credential generation, and identity generation; temporary sign-ins do not queue durable server replay. Android account replacement advances the identity transition before publishing replacement credentials.

Resilience and Maintainability Implications

  • observed — Possibly delivered progress remains retryable, while authentication-unavailable, unapproved cleartext, TLS-handshake, and platform-service refusals are excluded from sent marking. Separately, membership cancellation uses exact-claim, non-cancellable cleanup to enter reconciliation; ready-only background selection avoids automatically repeating those uncertain mutations.
Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title "fix(audiobooks): send offline listening on downloaded books to the server" matches the main change. The changeset queues whole-book playback positions from downloaded audiobooks for server …
Linked Issues check Passed Issue #957 has four coding requirements. (1) Whole-book positions go to POST /api/v2/sync/progress with their sample time: the PR routes eligible whole-book playback writes through FinalPlaybackPositi…
Out of Scope Changes check Passed The non-audiobook changes follow from the shared sent-marking rules, not from unrelated work. Video changes (PlayerViewModel offline capture, includeSent on the shared UserItemStatePort lookups, and t…
Description check Passed The description is specific and on-topic. It explains the problem (downloaded audiobook listening never updated server progress on Android), the solution (FinalPlaybackPositionWriter, whole-book check…
Full details: Title check

Explanation

The title "fix(audiobooks): send offline listening on downloaded books to the server" matches the main change. The changeset queues whole-book playback positions from downloaded audiobooks for server sync, and the description and objectives describe the same goal. The title is concise and specific, and it follows the conventional commit style.

Full details: Linked Issues check

Explanation

Issue #957 has four coding requirements. (1) Whole-book positions go to POST /api/v2/sync/progress with their sample time: the PR routes eligible whole-book playback writes through FinalPlaybackPositionWriter, with the sample time as updated_at, and adds the isWholeBookFile check in AudiobookTimeline.kt with a unit test. (2) Queued positions are sent when the server is reachable, not only on foreground: ServerReachabilityMonitor gains onServerReachable, PlayerInfraModule marks queued download progress due, and SyncWorker.enqueueNow replaces the backoff retry. Covered by the new drain path; SyncEngineTest covers the send and retry behavior. (3) Unsent local progress wins over the server's resume point when starting online: AudiobookPlayerViewModel captures unsent progress (includeSent) before the detail request and prefers it. (4) Multi-part books stay device-local: the whole-book check and the existing part-local suppression are kept, as #957 requires. The ebookAuthorities early return named in #957 is not changed in the summary. The PR states that #847 replaced it, and the emulator run shows queued offline progress reaching the server. This was not confirmed by reading RoomUserItemStateRepository at head, so that point rests on the PR description and validation evidence. The analysis relies on the whole-PR summary and the PR validation report; I did not inspect source hunks directly.

Full details: Out of Scope Changes check

Explanation

The non-audiobook changes follow from the shared sent-marking rules, not from unrelated work. Video changes (PlayerViewModel offline capture, includeSent on the shared UserItemStatePort lookups, and the video player's online resume skipping marked positions) apply the same marked-position semantics to downloaded video. The PR description and objectives disclose this. The reachability drain and SyncWorker.enqueueNow act on the shared download-progress outbox. Fake and test updates (TvNextUpSelectionHandoffTest, HomeScreenV2Test) only match the changed interface signatures. The offline requested-start change (chapter or bookmark) is disclosed and applies to audiobook playback. No change was found that is unconnected to #957 or the PR's stated objectives. Video resume behavior is not covered by #957; it is a side effect of the shared port change and is disclosed as such.

Full details: Description check

Explanation

The description is specific and on-topic. It explains the problem (downloaded audiobook listening never updated server progress on Android), the solution (FinalPlaybackPositionWriter, whole-book checks, sent marks, reachability-triggered drain, offline requested start position), validation steps on an emulator, risks, and follow-ups. It matches the changeset summaries across DAO, repository, SyncEngine, SyncWorker, PlayerInfraModule, ServerReachabilityMonitor, AudiobookPlayerViewModel, and AudiobookTimeline.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

@silo-triage silo-triage Bot added bug Something isn't working impact: usability Core flow broken or severely blocked needs-review Needs maintainer review to resolve uncertain classification, scope, or changed evidence. priority: P1 Core-path bug; painful workaround — next after P0 labels Nov 16, 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

Here are some automated review suggestions for this pull request.

Reviewed commit: b7694d8632

ℹ️ 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".

@macroscopeapp

macroscopeapp Bot commented Nov 16, 2026

Copy link
Copy Markdown

Downloaded-audiobook resume and offline chapter/bookmark start (AudiobookPlayerViewModel.kt) reach Android phone, tablet, foldable (folded and open), and TV. The body identifies phone-emulator evidence, but the shared-code note does not explain why the change cannot reach tablets or foldables, and it reports no TV run. Please add player captures for tablet, foldable folded and open, and TV, including a short recording of the offline chapter-start flow. The evidence page should also show the changed server-versus-local progress display and downloaded-video resume behavior (RoomUserItemStateRepository.kt, PlayerViewModel.kt) on the affected app surfaces.

Automated check: Macroscope check run agent (gpt-6-luna). Evidence was not reviewed for correctness.

Posted via Macroscope — Visible change evidence

"SELECT * FROM user_item_state " +
"WHERE serverId = :serverId AND accountId = :accountId AND profileId = :profileId " +
"AND contentId IN (:contentIds) AND positionSeconds > 0 " +
"AND (:includeSent OR serverUpdatedAtMs IS NULL) " +

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

kody code-review Kody Rules high

Reconciliation excludes progress with an unconfirmed send

An attempted send may not have reached the server, so excluding unresolved progress can replace it with an older server position. Remove the serverUpdatedAtMs exclusion and adjust the query API and reconciliation logic to protect pending and in-flight writes.

Kody rule violation: Use genuinely fresh reconciliation reads without overwriting newer local intent

Prompt for LLM
File android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/db/dao/UserItemStateDao.kt, line 112:

Reconciliation excludes progress with an unconfirmed send

Preserve pending and in-flight local progress during reconciliation even if a send was attempted without a definitive acknowledgment. The request may not have reached the server, or the reconciliation read may race it, so excluding these rows can replace valid local progress with an older server position. Remove this exclusion and adjust the query API and reconciliation logic so unresolved writes remain protected.

Kody rule violation: [Use genuinely fresh reconciliation reads without overwriting newer local intent](https://kodus.siloserver.org/settings/code-review/1247142403/kody-rules/423bfd53-9a51-4706-8e6e-d2ea0acc2907?teamId=ba9922fc-c0ea-4cf8-87bb-9d4f42ffc73e)

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

​

​

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This is deliberate. The maintainer chose Apple's rule for this PR (Silo-Server/silo-apple#1192): a send that may have arrived without an answer no longer beats the server's position at start, because newer progress from another device would win. The op is still sent again, and offline the position remains the resume point. The cost is disclosed under Risks.

🤖 Claude Code (claude-opus-5-5)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Understood. The suggestion conflicts with the maintainer’s deliberate choice: an uncertain send yields to the server’s position online, remains available for offline resume, and is retried. The risk that the send never arrived is already disclosed.

I would withdraw the suggestion for this PR. Would you like to document this exception for future reviews?

- Offline, the audiobook player resumes from this device's newest
  position before the cached server answer, so a synced rewind isn't
  undone by an older cached position.
- A failure to mark a position sent no longer turns its op terminal; the
  op stays queued.
- The video player reads the server's position again when the server took
  the queued one while the detail loaded, instead of using the older read.
- Without the server's total, several audio files no longer count as one
  whole-book file.

Refs #957

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@silo-kody

silo-kody Bot commented Nov 16, 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 ❌

From the adversarial review on #961: the RUNNING check and REPLACE weren't
atomic, so a drain starting in between was cancelled, and a membership send
cancelled mid-request leaves automatic retries.

The reachability drain is now its own unique work (APPEND_OR_REPLACE), and a
process-wide lock lets only one drain run at a time, so nothing is cancelled
and a request made while a drain finishes still gets its own drain. It never
starts its own retry chain; leftover work goes back to the main chain.

Refs #957

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@coderabbitai coderabbitai 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.

Actionable comments posted: 3

Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: fd03170b-0515-40da-bccd-776e8bc01013
Commits

Reviewing files that changed from the base of the PR and between 40d34e6 and b7694d8.

Files selected for processing: 18

  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/db/dao/DirtyOperationDao.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/db/dao/UserItemStateDao.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/repository/RoomUserItemStateRepository.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/sync/SyncEngine.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/sync/SyncWorker.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/di/PlayerInfraModule.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/network/ServerReachabilityMonitor.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/AudiobookPlayerViewModel.kt
  • android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/data/repository/RoomUserItemStateRepositoryTest.kt
  • android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/data/sync/SyncEngineTest.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/di/AndroidModule.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerViewModel.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/di/AndroidTvModule.kt
  • androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/detail/TvNextUpSelectionHandoffTest.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/audiobook/AudiobookTimeline.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/repository/port/UserItemStatePort.kt
  • shared/src/commonTest/kotlin/org/siloserver/silo/audiobook/AudiobookTimelineTest.kt
  • shared/src/commonTest/kotlin/org/siloserver/silo/viewmodel/HomeScreenV2Test.kt

Included review availability: This review used your included allowance. 0 included reviews remain after this review. Your included PR review attempts over the past 7 days set your current allowance at 1 review per hour.

userItemStatePort.localPosition(contentId, fileId, includeSent = true)
} else {
// One the server took while the detail was loading is newer than that answer.
userItemStatePort.localPosition(contentId, fileId) ?: unsentBefore

@coderabbitai coderabbitai Bot Nov 16, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Major · Data Integrity & Integration · Quick win

Do not restore a sample that synchronization has already marked sent.

If synchronization marks unsentBefore before the metadata request reads server progress, the server can return a newer position from another device. The second unsent lookup then returns null, but this fallback restores the older sample. detailPos selects that sample over the live server answer.

Preserve enough sample identity and ordering information to distinguish a still-pending sample from one already covered by the server read. Do not assume that every sample marked during this load is newer than the response.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in 49afc0a and 2755db8: when the queued sample disappears during the metadata read, the video player re-reads the server's position (and then prefers any local position queued meanwhile) instead of restoring the earlier sample. It falls back to that sample only if the re-read fails.

🤖 Claude Code (claude-opus-5-5)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Analysis chain

Script executed:

#!/bin/bash
set -u
file="androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerViewModel.kt"
echo '=== Current revision ==='
git rev-parse HEAD
echo '=== Target outline ==='
ast-grep outline "$file" --items all --match 'tryLocalPlayback' --view expanded
echo '=== Target code ==='
rg -n -C 26 'val unsentBefore = userItemStatePort\.localPosition' "$file"
echo '=== Metadata helper and related call sites ==='
rg -n -C 18 --type kotlin 'fun loadLocalWatchMetadata|loadLocalWatchMetadata\('
echo '=== Metadata and resume tests ==='
rg -n -C 4 --type kotlin 'unsentBefore|server.*re.?read|re.?read.*server|sent.*detail|detail.*sent|loadLocalWatchMetadata'
echo '=== Applicable repository guidance files ==='
for f in AGENTS.md androidApp/AGENTS.md androidApp/src/AGENTS.md androidApp/src/androidMain/AGENTS.md androidApp/src/androidMain/kotlin/AGENTS.md androidApp/src/androidMain/kotlin/org/AGENTS.md androidApp/src/androidMain/kotlin/org/siloserver/AGENTS.md androidApp/src/androidMain/kotlin/org/siloserver/silo/AGENTS.md androidApp/src/androidMain/kotlin/org/siloserver/silo/android/AGENTS.md androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/AGENTS.md androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/AGENTS.md androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/AGENTS.md; do
  if [ -f "$f" ]; then echo "=== $f ==="; cat "$f"; fi
done

Length of output: 117415


@Quick104 The re-read addresses the successful-read case. One case remains: if sync marks the sample sent before the first detail read, that read can return a newer server position. If the re-read then fails, Line 7022 restores the earlier sample instead.

The first answer can also be stale if sync finishes after that read. Please preserve enough ordering information to distinguish these cases, and add a regression test for both orderings when the re-read fails.

I’m not marking the finding as addressed yet.

You are interacting with an AI system.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

That fallback is deliberate. When the queued sample settled during the first read and the re-read then fails, the player has no fresh server answer and can't tell which side is newer. It follows Apple's onlineContext here: without an answer, the listening the server just took stands. The audiobook path does the same. This needs the first read to succeed and the immediate re-read to fail, so I'm not adding ordering state or a test for it (the repository keeps tests to critical behavior). Leaving the thread open for the maintainer.

🤖 Claude Code (claude-opus-5-5)

Quick104 and others added 2 commits November 16, 2026 02:53
…ndexed alternates

From Kody on #961:
- After re-reading the server's position, the video player checks for a
  local position queued meanwhile and prefers it.
- Without the server's total, files sharing one part index are alternates
  of that part, so each still counts as the whole book; only several
  unlabeled files are rejected.

Refs #957

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…cks the resume point

From CodeRabbit on #961: the queued position could be marked sent between
the check that decided whether to re-read the detail and the final local
read, so the player resumed from the older detail. The re-read now happens
inside the resume lookup, right after its own unsent read.

Refs #957

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@silo-triage silo-triage Bot added size/XL 500–999 added + deleted lines (all files); change volume, not priority. and removed size/L 200–499 added + deleted lines (all files); change volume, not priority. labels Nov 16, 2026
@silo-kody

silo-kody Bot commented Nov 16, 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 ❌

…eep a retry for leftover work

From Kody on #961:
- After the audiobook player re-reads the detail, it reads local progress
  again, so a position queued during that read wins over its answer.
- A drain-now worker that leaves work behind appends a main-chain drain
  (APPEND_OR_REPLACE) instead of KEEP, which a finishing main drain could
  drop, leaving that work with no retry.

Refs #957

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@Quick104 Quick104 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Adversarial review (gpt-6.1-sol, reviewed 932a6dd)

One confirmed P2 finding. An isolated coroutine replay of the unchanged resume method reproduces the pending-position race. All 51 focused SyncEngine and RoomUserItemStateRepository tests passed; the sent-mark SQL also preserved newer samples and scope boundaries in direct SQLite checks.

AI disclosure: gpt-6.1-sol via Codex, read-only review.

@silo-kody

silo-kody Bot commented Nov 16, 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 ❌

@Quick104
Quick104 merged commit 08213c1 into main Nov 16, 2026
10 checks passed
@Quick104
Quick104 deleted the fix/957-offline-audiobook-progress-sync branch November 16, 2026 14:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working impact: usability Core flow broken or severely blocked needs-review Needs maintainer review to resolve uncertain classification, scope, or changed evidence. priority: P1 Core-path bug; painful workaround — next after P0 size/XL 500–999 added + deleted lines (all files); change volume, not priority.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Parity: send offline audiobook listening to the server (from Silo-Server/silo-apple#1192)

1 participant