You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
fix(audiobooks): send offline listening on downloaded books to the server - #961
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.
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.
Following Apple's rule, a position marked "may have arrived" that never reached the server (a proxy 502 during a restart, a write timeout) loses at start to the server's older position, and the new session's samples then supersede it.
Offline, cards, detail and the Downloads tab don't show a position sent without an answer, while the players resume from it, until the resend lands.
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.
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.
…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]>
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.
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.
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.
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: 4
Check name
Status
Explanation
Title check
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
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
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
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
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.
The reason will be displayed to describe this comment to others. Learn more.
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.
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)
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.
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]>
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]>
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.
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.
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.
@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.
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.
…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-triageBot
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
…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]>
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
bugSomething isn't workingimpact: usabilityCore flow broken or severely blockedneeds-reviewNeeds maintainer review to resolve uncertain classification, scope, or changed evidence.priority: P1Core-path bug; painful workaround — next after P0size/XL500–999 added + deleted lines (all files); change volume, not priority.
1 participant
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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_POSITIONv2 throughPOST /api/v2/sync/progresswithupdated_at); the audiobook player never used it. TheebookAuthoritiesearly 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.
FinalPlaybackPositionWriterwith the time it was sampled, about every 10 s of listening and on pause, seek and close. The server merges byupdated_at, newest first, so an earlier position played later still wins.isWholeBookFilemust 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.onlineContext).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.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.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:
SyncEngineTest.downloadProgressIsSentWithItsEventTimeAndThenStopsOverridingTheServerfails 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),lintVitalReleaseandassembleDebug(phone, TV) pass. One unrelatedCatalogLetterIndexViewModelTestfailure 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.Evidence: https://evidence.siloserver.org/r/silo-android/957-offline-audiobook-sync/
Risks
serverUpdatedAtMsnow holds the sample time a position was sent at, not a server timestamp.Follow-ups
updated_aton item user data (or in the/sync/progressanswer) would let the client compare times instead of inferring from the send outcome.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 (reuseRequestMutationFailure.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'sonlineContext).AI disclosure
🤖 Generated with Claude Code
Note
Send offline listening progress on downloaded audiobooks to the server
FinalPlaybackPositionWriter. Periodic saves are throttled to submit only when the position changes by at least a 10-second interval.isWholeBookFilepredicate in AudiobookTimeline.kt, which requires the file to cover at least 90% of the server total (or be a single/same-part audio candidate).SyncEngineretains accepted progress locally with aserverUpdatedAtMssent 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.includeSentoption acrossUserItemStatePort, so offline resume uses sent-inclusive samples and online reads exclude them. On server reachability, pending download progress is made due and drained immediately viaenqueueNowonSyncWorker.localPosition,localPositionForContent,localPlaybackProgress, andlocalPlaybackProgressForContentin UserItemStatePort.kt changed signatures; out-of-tree implementations must add theincludeSentargument.Macroscope summarized a101ed3.