Skip to content

fix(audiobooks): sort and show audiobooks by the length of their files - #3167

Merged
Quick104 merged 9 commits into
Silo-Server:mainfrom
Rhainland:fix/1253-audiobook-duration
Oct 31, 2026
Merged

Quick104 merged 9 commits into
Silo-Server:mainfrom
Rhainland:fix/1253-audiobook-duration

Conversation

@Rhainland

@Rhainland Rhainland commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Related issue: #1253
Validation tasks: changes #1256 C1; changes Silo-Server/silo-apple#339 C1; changes Silo-Server/silo-apple#340 C1; changes Silo-Server/silo-android#349 C1; changes Silo-Server/silo-android#350 C1

Audiobook Duration sorting, runtime filters and browse cards use an absent or provider-derived runtime that can describe a different edition. This change derives the item's runtime from its active recording files.

Approach

The longest active recording copy determines runtime. File durations are summed per library and canonical recording root, rounded to the nearest minute with a one-minute minimum. Database statement triggers maintain the value after file insertions, changes, moves, missing marks and deletions. They lock affected audiobook items before aggregating in a fresh statement, and exclude other item types before reading their files. Trigger installation commits before the backfill. The migration uses the same function in batches of at most 100 books, commits each batch, bounds lock waits to five seconds, and can replay an interrupted run without rewriting corrected values. File triggers acquire the item lock before shared library stats, matching the item upsert order.

Metadata enrichment, manual refresh and Identify preserve the file-derived value. A locked admin runtime remains authoritative; unlocking it restores file duration immediately. Books with no positive active duration retain their stored value.

The native v1 and v2 values are corrected without changing field names, types or units. Duration sorting, paging, runtime rules and item responses share this value. Audiobook group totals and Audiobookshelf responses retain their existing library-scoped duration calculations. Jellyfin does not expose audiobooks. The query layer and client wire contracts are unchanged; docs/catalog-api.md documents the runtime rule.

Validation

  • PostgreSQL regressions reproduced stale values on the original PR head: missing/deleted longest copy, physical-root replacement, generic metadata persistence, ignored runtime locks, concurrent scans and copy reassignment. The repaired cases pass. Unlocking and unlocked metadata edits also failed before their correction.
  • A separate file-only concurrency test observes a database lock wait without an item upsert. A mixed metadata/missing-writer regression reproduced PostgreSQL deadlock 40P01 before the lock-order correction. The Goose backfill test verifies three committed batches without a retained installation lock, an idempotent retry, and rollback. All database tests are selected in scripts/ci/db-contracts.txt.
  • Full scanner, audiobooks, catalog and migration package suites passed against a disposable PostgreSQL database. Targeted vet, changed-line lint, migration validation, migration ledger and local-path checks passed.
  • Live verification on an isolated sandbox: removing a 631-second copy while retaining a 629-second copy left 11 minutes before repair. After repair, the normal scan stored 10 minutes even with retained files skipped as unchanged. The admin API also preserves a locked edit and restores file duration immediately on unlock. Independent catalog and database reads agree; runtime >= 11 returns no items. Desktop and phone-width captures show the same result.
  • The named C1 cases need retesting on the merged build. Existing agent results do not establish human acceptance. Native Apple and Android apps were not exercised in this review; their existing runtime requests need no implementation change. The manual's audiobook, compatibility, library and feature pages remain accurate.

Evidence

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

Before: original PR head 8855efba4; after: 4d8f037cca876dfadf30eb6b02962fcc53c8b86e. Same synthetic files, library, filters and viewport sizes. The before build endpoint lacked revision metadata; the deployed source identifies it. The after build reports the final revision explicitly.

Risks

Backfill replaces unlocked provider runtimes for audiobooks with positive-duration files. Those old values are not retained. Down removes runtime maintenance and restores the prior stats trigger function, but cannot restore replaced values. File writes add runtime maintenance for affected audiobooks; concurrent writes serialize on their item rows. Statement transition tables also add work to file writes for other types, which return before duration aggregation.

Checklist

  • I read and can explain the complete diff.
  • This pull request addresses one concern.
  • Each new test meets "Decide what to test" in CONTRIBUTING.md.
  • The Evidence section shows the visible change.

AI Disclosure

  • Harness: Claude Code (T3 Code)
  • Tool(s): Claude Code, Codex CLI, GitHub CLI, Playwright, Docker, ffmpeg
  • Model(s): claude-opus-5-5; gpt-6.1-sol (review)
  • Involvement: Fully AI-generated, human verified
  • Adversarial review: Independent Claude Opus 5.5 and GPT 6.1 Sol reviews of the branch diff (correctness, repo standards, the bug as described). GPT found that the first backfill version summed duplicate copies in one library; fixed (per-root totals) with a test row, and both reviewers checked the fix with no findings. Opus questioned whether the enrichment test is worth keeping; it is, because it guards against provider values overwriting file durations again.

Review repairs: gpt-6.1-sol in T3 Code using the Codex provider. Tools: GitHub CLI, Go, PostgreSQL, Docker, Playwright and ffmpeg. Claude Code with claude-opus-5-5 supplied two read-only reviews. Review changes and evidence were verified by agents; native-device and human acceptance remain pending.

Note

Derive audiobook runtime from file durations via database triggers and backfill

Audiobook runtime is now the longest active copy's summed file duration, rounded to minutes with a minimum of one, computed per library and canonical recording root.

  • Adds refresh_audiobook_runtime plus statement triggers on media_files, so file inserts, deletes, and relevant updates recompute the runtime in 20261028150609_audiobook_runtime_from_files.sql. A backfill procedure handles existing unlocked audiobooks in batches of 100.
  • catalog.ItemRepository.UpdateMetadataTx now calls refresh_audiobook_runtime in-transaction when a metadata update sets runtime or locked fields, and the upsert in writeItem keeps an existing audiobook's runtime instead of overwriting it.
  • Enrichment no longer persists the provider's runtime, since it may describe a different edition; locked runtimes stay locked until unlocked.
  • Risk: the migration changes trigger behavior on media_files (new runtime triggers and reworked file-stat trigger with item-row locks); rollback removes these and restores the prior stats trigger. Check audiobooks.Enricher.persist in enrichment.go for downstream consumers relying on provider runtime values.

Macroscope summarized 4d8f037.

@silo-triage silo-triage Bot added the size/M 50–199 added + deleted lines (all files); change volume, not priority. label Oct 27, 2026
@silo-kody

silo-kody Bot commented Oct 27, 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 Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review.

Recent 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: fe5fe35e-5559-447b-ab97-09c7f26c0341
Commits

Reviewing files that changed from the base of the PR and between cb22409 and 4d8f037.

Files selected for processing: 4
  • internal/scanner/book_skip_postgres_test.go
  • migrations/audiobook_runtime_from_files_test.go
  • migrations/sql/20261028150609_audiobook_runtime_from_files.sql
  • scripts/ci/db-contracts.txt

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

Walkthrough

Audiobook runtime now derives from active recording files and updates when those files change. Metadata enrichment no longer writes provider runtime. Runtime edits and locks trigger a refresh, while audiobooks without positive file durations retain their stored runtime.

Changes: Audiobook runtime

Layer / File(s) Summary
Derive and backfill runtime from active files
migrations/sql/20261028150609_audiobook_runtime_from_files.sql, migrations/audiobook_runtime_from_files_test.go
The migration calculates runtime from active file durations, selects the greatest recording-root total, and refreshes affected audiobooks when files change. It also backfills existing records. Migration tests cover file states, locks, reassignment, batching, and rollback.
Preserve runtime across application writes
internal/catalog/item_repo.go, internal/audiobooks/enrichment.go, internal/audiobooks/enrichment_test.go, internal/scanner/book_skip_postgres_test.go, scripts/ci/db-contracts.txt, docs/catalog-api.md
Item writes preserve stored audiobook runtime, and metadata updates refresh runtime when runtime or lock fields change. Enrichment leaves provider runtime unset. PostgreSQL tests cover file changes, locks, and concurrent writes; database contracts and documentation describe the behavior.

Priority: Normal

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix

Possibly related issues

  • Issue 1253: The pull request changes audiobook runtime used for display, sorting, filtering, and paging.
  • Issue 3161: The pull request stops enrichment from copying provider runtime and derives runtime from item files. It does not change the partial-match rule.
  • Issue 1254: The pull request adds runtime backfill and tests runtime updates during scanning.
  • Issue 1256: The pull request changes runtime used for audiobook display and duration-based filtering and sorting.
  • Issue 1255: The pull request changes runtime updates during rescans and preserves locked runtime edits.

Possibly related PRs

  • Silo-Server/silo-server#3108: Both changes define duration for multi-file audiobooks, for playback history and catalog runtime respectively.
  • Silo-Server/silo-server#3169: Both changes group positive file durations by recording root and select the longest copy, for listened-history duration and catalog runtime respectively.

Suggested labels: impact: usability

Suggested reviewers: quick104

Merge Risk: Minimal · up to 4d8f0

No actionable issue remains from this review; the PR is mergeable after normal checks.

Security architecture risk: Low · up to 4d8f0

Runtime locks and transactional updates limit the impact of the change. The main risks are coordinating application and database rollback and preserving the new duration rule across alternate write paths. Prior durations cannot be restored automatically, and deployed database access controls were not verified.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • observed — The new derived-state sink updates runtime and updated_at for qualifying audiobook items. Its input scope is content-ID based and spans recording copies across library folders; it is not restricted to the library that caused the file mutation. This establishes shared catalog-state scope, not demonstrated cross-tenant access.

Trust Boundaries and Controls

  • observed — The flagged Go public-entrypoint symbols are PostgreSQL tests and fixture helpers. They do not establish production API reachability. The material production boundary is database execution through file mutations and the catalog metadata writer; public-schema placement alone does not establish an unauthenticated API.

Resilience and Maintainability Implications

  • inferred — Runtime refresh participates in the triggering file statement or metadata transaction, so refresh errors fail that write rather than independently committing derived state. Backfill deliberately has different recovery semantics: completed batches remain committed after interruption, and rerunning refresh can converge without restoring prior provider values.
Pre-merge checks: Passed 5
Check name Status Explanation
Title check Passed The title names the audiobook sort and display change and its basis in file lengths. The changeset derives audiobook runtime from active recording files, and that runtime drives duration sorting, runt…
Description check Passed The description states the problem, which is that audiobook duration sorting, runtime filters, and browse cards rely on provider-derived runtime. It then explains the approach: file-derived runtime wi…
Docstring Coverage Passed Docstring coverage is inconclusive: files from earlier reviews still need to be rechecked within the check's analysis limits. Not blocking.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names the audiobook sort and display change and its basis in file lengths. The changeset derives audiobook runtime from active recording files, and that runtime drives duration sorting, runtime filters, and browse cards. The title is specific and matches the main change.

Full details: Description check

Explanation

The description states the problem, which is that audiobook duration sorting, runtime filters, and browse cards rely on provider-derived runtime. It then explains the approach: file-derived runtime with database triggers, a batched backfill, and preservation through enrichment and locks. It also lists validation and risks. It is directly related to the changeset.

Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

@silo-triage silo-triage Bot added bug Something isn't working evidence-required Needs before-and-after evidence before the Evidence check passes go Pull requests that update go code priority: P2 Limited scope, workaround exists, or polish labels Oct 27, 2026
Comment thread internal/scanner/audiobook_scan.go Outdated
Comment on lines +1164 to +1165
if minutes := audiobookRuntimeMinutes(book.Files); minutes > 0 {
item.Runtime = minutes

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 Bug medium

Inconsistent shared audiobook runtime results from unconditionally assigning the current folder's runtime, making the last reconciled copy determine the value rather than following the backfill's longest-copy selection. Because findAudiobookDuplicate accepts duration differences up to 0.5%, reconciling 36,000-second and 36,170-second copies can flip the same item's duration between 600 and 603 minutes; use a consistent active-copy selection policy for scanning and backfill.

Prompt for LLM

File internal/scanner/audiobook_scan.go:

Line 1164 to 1165:

Inconsistent shared audiobook runtime results from unconditionally assigning the current folder's runtime, making the last reconciled copy determine the value rather than following the backfill's longest-copy selection. Because findAudiobookDuplicate accepts duration differences up to 0.5%, reconciling 36,000-second and 36,170-second copies can flip the same item's duration between 600 and 603 minutes; use a consistent active-copy selection policy for scanning and backfill.

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.

Fixed in f43ecd8: a scan now keeps the longest active copy's runtime, the same rule as the backfill, so the order copies are scanned in no longer changes it.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Thanks for the fix in f43ecd85b. Keeping the longest active copy’s runtime makes scans consistent with the backfill and removes scan-order dependence.

ON ab.content_id = mf.content_id AND ab.type = 'audiobook'
WHERE mf.missing_since IS NULL
AND mf.duration > 0
GROUP BY mf.content_id, mf.media_folder_id, mf.canonical_root_path

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 Bug medium

Runtime overcounting occurs when grouping by canonical_root_path merges separate legacy copies: migration 076 adds the column with DEFAULT '' without backfilling existing rows, so two copies of a ten-hour recording in the same media folder produce a twenty-hour runtime during this upgrade. Resolve a recording root for legacy rows before aggregating and add an empty-root regression fixture.

Prompt for LLM

File migrations/sql/20261027163759_audiobook_runtime_from_files.sql:

Line 25:

Runtime overcounting occurs when grouping by canonical_root_path merges separate legacy copies: migration 076 adds the column with DEFAULT '' without backfilling existing rows, so two copies of a ten-hour recording in the same media folder produce a twenty-hour runtime during this upgrade. Resolve a recording root for legacy rows before aggregating and add an empty-root regression fixture.

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.

Not changing this: audiobook files never have an empty canonical_root_path. Audiobook scanning arrived after migration 076 added the column, and the audiobook scanner has always written the root (the folder path at first, the resolved physical path since symlinks were followed), so no upgraded audiobook row keeps the '' default. A rescan also rebuilds any book whose stored root differs from the folder's physical path.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Agreed—the suggestion was a false positive. I assumed the '' default introduced by migration 076 could occur on legacy audiobook rows, but your timeline rules that out: audiobook scanning came later and has always populated canonical_root_path.

The rescan behavior also handles roots that differ from the physical path. There’s no supported upgrade scenario behind my overcounting claim, so neither the fallback nor the empty-root regression fixture is warranted. I withdraw the suggestion.

@macroscopeapp

macroscopeapp Bot commented Oct 27, 2026

Copy link
Copy Markdown

The audiobook browse C1 results for Web, iPhone/iPad, tvOS, Android phone/tablet, and Android TV are all Not run, so no recorded human result is invalidated and no blocker is recorded. Each C1 covers sort/filter; these clients send runtime to the server catalog, and this PR makes audiobook runtime file-derived. That changes Duration/Runtime sort order (and the Web browse card's runtime label). The current unblocks wording is inaccurate. The PR should explain this order/display change and state that these C1s need validation on the merged build; as their results are Not run, this is initial validation.

Please replace the line with:

Validation tasks: changes #1256 C1; changes Silo-Server/silo-apple#339 C1; changes Silo-Server/silo-apple#340 C1; changes Silo-Server/silo-android#349 C1; changes Silo-Server/silo-android#350 C1

Automated check: Macroscope check run agent (gpt-6-luna). No validation was performed.

Posted via Macroscope — v1 validation impact

Audiobook runtime came only from the metadata provider, which describes
whichever edition it matched, so scanned books had runtime 0 and sorted as
unknown under Duration while a matched book could show another edition's
length.

The audiobook scan now sets media_items.runtime from the summed probed file
durations (nearest minute, at least one), enrichment no longer copies the
provider's runtime, and a migration backfills existing audiobooks from
audiobook_item_file_stats. Sort, cursor paging, runtime rules and the item's
runtime field all read the same column, so they agree without query changes.
Two copies of the same recording in one library share an item, and the
per-library file total added them together, doubling the book's runtime.
Sum files per recording root and keep the longest copy instead.
Duplicate copies of one recording share an item. A scan set the runtime from
whichever copy it wrote last, while the backfill takes the longest copy, so
the two could disagree by a few minutes and the runtime moved between scans.
The scan now keeps the longest active copy too.
…grations

Main gained migrations dated after this one. Give the backfill a new timestamp so it still applies last.
@Rhainland
Rhainland force-pushed the fix/1253-audiobook-duration branch from 041cee3 to 8855efb Compare October 28, 2026 15:07
@silo-triage silo-triage Bot added size/L 200–499 added + deleted lines (all files); change volume, not priority. and removed size/M 50–199 added + deleted lines (all files); change volume, not priority. labels Oct 28, 2026
@silo-kody

silo-kody Bot commented Oct 28, 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 ❌

@macroscopeapp

macroscopeapp Bot commented Oct 28, 2026

Copy link
Copy Markdown

The change is visible, but the Evidence description covers only the Web library's Duration sort. It does not show the runtime-filter result changes, or the sort/filter behavior on iPhone/iPad, tvOS, Android phone/tablet, and Android TV. Please add before-and-after evidence for the same filter query on Web and for the affected native surfaces, using the same data and naming each surface and build.

Suggested fix: Extend the linked evidence page with those before-and-after captures.

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

Posted via Macroscope — Visible change evidence

Comment thread internal/scanner/audiobook_scan.go Outdated
Comment on lines +967 to +969
if other := runtimeMinutesFromSeconds(otherSeconds); other > audiobookRuntimeMinutes(book.Files) {
item.Runtime = other
}

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 Bug high

Missing runtime invalidation in internal/scanner/audiobook_scan.go leaves the removed longest copy's runtime on the item indefinitely, causing stale Duration sorting and card runtimes: presentation writes alone recalculate the maximum, reconcileAudiobookMissingFiles marks removed files missing afterward, and unchanged surviving copies skip those writes. Recompute affected items after missing-file reconciliation, including when surviving copies remain unchanged.

Prompt for LLM

File internal/scanner/audiobook_scan.go:

Line 967 to 969:

Missing runtime invalidation in internal/scanner/audiobook_scan.go leaves the removed longest copy's runtime on the item indefinitely, causing stale Duration sorting and card runtimes: presentation writes alone recalculate the maximum, reconcileAudiobookMissingFiles marks removed files missing afterward, and unchanged surviving copies skip those writes. Recompute affected items after missing-file reconciliation, including when surviving copies remain unchanged.

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

Choose a reason for hiding this comment

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

Confirmed with a PostgreSQL regression: marking or deleting the longest copy leaves 603 minutes instead of the remaining 600. I am fixing runtime maintenance at the file-write boundary so scan cleanup, playback missing checks, moves, and deletion all use it. No author action is needed. Reviewed with Codex in T3 Code (gpt-6.1-sol).

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Thanks for confirming with the PostgreSQL regression. Maintaining runtime at the file-write boundary addresses the broader issue, not just scan reconciliation.

The key regression case is that marking or deleting the 603-minute copy reduces runtime to 600 minutes even when the surviving copy is unchanged. The fix should cover moves and playback missing checks as well.

No additional author action is needed here.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Fixed in b960759, included in cb22409. File INSERT/UPDATE/DELETE triggers now recompute affected audiobook runtimes after the file changes, covering missing marks, deletion and reassignment across writers. PostgreSQL regressions cover marking and deleting the longest copy. On the final sandbox build, a normal scan marked the removed 631-second copy missing and lowered runtime to 10 minutes from the remaining 629-second copy, even though surviving files were skipped as unchanged.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Thanks—the reported fix in b96075985, included in cb224091c, addresses the original finding at the file-write boundary rather than only during scan reconciliation.

The sandbox result covers the key failure case: removing the 631-second copy lowers runtime to 10 minutes from the remaining 629-second copy, even when surviving files are skipped as unchanged. The PostgreSQL regressions also cover marking and deleting the longest copy.

Based on that evidence, I consider this finding addressed. No further change is requested for this comment; merged-build C1 retesting and native-device/human acceptance remain separate pending checks.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1


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: e5edcd16-67dd-491b-898f-5c744c0745a1
Commits

Reviewing files that changed from the base of the PR and between 041cee3 and 8855efb.

Files selected for processing: 6
  • docs/catalog-api.md
  • internal/scanner/audiobook_scan.go
  • internal/scanner/book_skip_postgres_test.go
  • migrations/audiobook_runtime_from_files_test.go
  • migrations/sql/20261028150609_audiobook_runtime_from_files.sql
  • scripts/ci/db-contracts.txt

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

Comment thread internal/scanner/audiobook_scan.go Resolved

@Quick104 Quick104 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verified at 8855efba4. The new findings below were reproduced with PostgreSQL regression tests. The existing concurrency and missing-copy findings are also confirmed; I am handling those in their existing threads.

Reviewed with Codex in T3 Code (gpt-6.1-sol) and one independent Claude Opus 5.5 round (claude-opus-5-5).

Comment thread internal/scanner/audiobook_scan.go Resolved
Comment thread internal/audiobooks/enrichment.go Resolved
Comment thread internal/scanner/audiobook_scan.go Resolved
@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 Oct 28, 2026
@silo-kody

silo-kody Bot commented Oct 28, 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 commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Reviewed head: 4d8f037cca876dfadf30eb6b02962fcc53c8b86e.

Fit: 9/10 · Readiness: 9/10 — ready

This fixes incorrect audiobook Duration sorting, filters and cards at the file-write boundary. The branch now maintains the longest active copy after missing marks, deletion, moves and concurrent writes; protects file duration from metadata refresh; honors runtime locks; and restores file duration when a lock is removed. The fix replies above identify the commits and evidence. No substantive finding remains from this review.

Verification: all selected CI jobs are green on the reviewed head. CodeRabbit and Kody completed with no new findings. The scanner, audiobooks, catalog and migration package suites pass against disposable PostgreSQL, along with targeted vet, changed-line lint and migration/ledger/path checks. Regressions failed on the original head for stale copies, metadata overwrite, locks and concurrent scans. A mixed metadata/missing-writer test reproduced deadlock 40P01 and passes after aligning item/stats lock order. A real Goose test verifies three committed backfill batches, release of installation locks before backfill, idempotent retry and rollback. On the final sandbox build, a normal scan changed 11 to 10 minutes after the longest copy went missing while surviving files were skipped. Catalog queries, desktop/mobile views, and an admin API lock/unlock followed by independent reads agree.

Validated features: #1256 C1; Silo-Server/silo-apple#339 C1; Silo-Server/silo-apple#340 C1; Silo-Server/silo-android#349 C1; Silo-Server/silo-android#350 C1. These cases need retesting on the merged build. Existing agent runs do not establish human acceptance; this review exercised web and API behavior, without native-device testing. No validation records or board status were changed.

Apple/Android requests and wire contracts need no implementation change. Jellyfin excludes audiobooks. Group and Audiobookshelf durations retain their library-scoped calculations, now distinguished in the API docs. The manual's audiobook, compatibility, library and feature pages remain accurate.

Independent review: two read-only Claude Code rounds with claude-opus-5-5 at high effort. The first confirmed the scanner defects and broadened the repair to all file writers. The final round reviewed 424d9fa8a; its non-audiobook aggregation cost and unlock findings are fixed in cb224091c, with file-only concurrency coverage added and verified. Later Kody findings exposed backfill table-lock retention and a shared-stats lock inversion; both were independently reproduced and fixed in 4d8f037cc. Those independent reviews used source inspection; the parent performed the database and sandbox checks. Runtime performance on a large library was not measured.

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

Review and repairs: gpt-6.1-sol in T3 Code using the Codex provider, with GitHub CLI, Go, PostgreSQL, Docker, Playwright and ffmpeg. Human acceptance remains pending.

@macroscopeapp

macroscopeapp Bot commented Oct 28, 2026

Copy link
Copy Markdown

The audiobook runtime now changes native browse sorting, filtering, and displayed durations through the values returned by internal/catalog/item_repo.go and the runtime-maintenance migration. The linked evidence is described as before-and-after desktop and phone-width web captures, but the PR says native apps were not exercised. Please add before-and-after captures of the same audiobook query on the affected iPhone/iPad, tvOS, Android phone/tablet, and Android TV surfaces, or explain why those captures are unavailable.

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

Posted via Macroscope — Visible change evidence

REFERENCING OLD TABLE AS old_files
FOR EACH STATEMENT EXECUTE FUNCTION public.audiobook_runtime_media_files_trigger();

SELECT public.refresh_audiobook_runtime(array_agg(content_id))

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

File-write blocking in migrations/sql/20261028150609_audiobook_runtime_from_files.sql persists throughout the full-library backfill because the default Goose transaction includes three CREATE TRIGGER statements whose SHARE ROW EXCLUSIVE locks on media_files block inserts, updates, and deletes until commit, including while the backfill locks every audiobook and aggregates its runtime. Commit trigger installation before the backfill, for example in a separate migration, and process bounded, resumable batches; StatementBegin/StatementEnd does not create a transaction boundary.

Kody rule violation: Make denormalization migrations resumable with bounded lock and retry costs

Prompt for LLM

File migrations/sql/20261028150609_audiobook_runtime_from_files.sql:

Line 95:

File-write blocking in migrations/sql/20261028150609_audiobook_runtime_from_files.sql persists throughout the full-library backfill because the default Goose transaction includes three CREATE TRIGGER statements whose SHARE ROW EXCLUSIVE locks on media_files block inserts, updates, and deletes until commit, including while the backfill locks every audiobook and aggregates its runtime. Commit trigger installation before the backfill, for example in a separate migration, and process bounded, resumable batches; StatementBegin/StatementEnd does not create a transaction boundary.

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

Choose a reason for hiding this comment

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

Confirmed and fixed in 4d8f037. The previous migration's real Goose test recorded one backfill transaction with the media_files SHARE ROW EXCLUSIVE installation lock still held. Up now uses NO TRANSACTION, separate committed trigger statements, and a procedure that commits each batch of at most 100 books with a five-second lock timeout. CREATE OR REPLACE makes interrupted installation safe to replay; corrected runtimes are not rewritten on retry. The Goose test now records three backfill transactions without the installation lock and passes retry and Down checks. The final sandbox also replayed the revised migration successfully through normal startup Goose.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Thanks for confirming. Based on the changes and test results you described for 4d8f037cc, the original concern is addressed:

  • Trigger installation commits before backfill, so its SHARE ROW EXCLUSIVE lock no longer spans the backfill.
  • Batches of at most 100 books commit independently, with a five-second lock timeout bounding lock waits.
  • The reported Goose tests cover transaction separation, retry, and Down behavior; normal-startup sandbox replay also passed.

I consider this suggestion resolved based on your report; I haven’t independently inspected the revised commit or test output.

Comment on lines +25 to +29
PERFORM 1 FROM public.media_items
WHERE content_id = ANY(p_content_ids) AND type = 'audiobook'
AND NOT (7 = ANY(COALESCE(locked_fields, '{}'::integer[])))
ORDER BY content_id
FOR NO KEY UPDATE;

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 Bug high

Lock-order inversion in migrations/sql/20261028150609_audiobook_runtime_from_files.sql causes deadlocks: MarkMissing locks audiobook_item_file_stats through the existing row trigger before requesting the new media_items row lock, while upsertAudiobookPresentationTx locks media_items through UpsertTx before requesting the same stats row through the existing media_items trigger. Concurrent scans and missing-file updates for the same audiobook/library therefore abort one transaction; acquire item and stats locks in the same order on both paths and add a mixed-writer concurrency test.

Prompt for LLM

File migrations/sql/20261028150609_audiobook_runtime_from_files.sql:

Line 25 to 29:

Lock-order inversion in migrations/sql/20261028150609_audiobook_runtime_from_files.sql causes deadlocks: MarkMissing locks audiobook_item_file_stats through the existing row trigger before requesting the new media_items row lock, while upsertAudiobookPresentationTx locks media_items through UpsertTx before requesting the same stats row through the existing media_items trigger. Concurrent scans and missing-file updates for the same audiobook/library therefore abort one transaction; acquire item and stats locks in the same order on both paths and add a mixed-writer concurrency test.

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

Choose a reason for hiding this comment

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

Confirmed and fixed in 4d8f037. A mixed item-upsert/missing-writer PostgreSQL regression reproduced deadlock 40P01 on cb22409. The existing file-stats row trigger now locks the affected audiobook item before updating shared library stats, matching the item-upsert order. The mixed-writer regression now passes, as do the scanner, catalog and migration suites. The normal sandbox scan still lowers runtime after the longest copy goes missing, including when surviving files are skipped.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Thanks for confirming. Based on your report, 4d8f037 addresses the original deadlock finding by making both paths lock the audiobook item before updating shared library stats.

The mixed-writer regression is especially useful: it reproduced 40P01 on the previous revision and now passes. The passing suites and sandbox scan also support that runtime correction still works when surviving files are skipped as unchanged.

I haven’t independently inspected the fix or rerun those tests; this assessment is based on the evidence you reported.

@coderabbitai coderabbitai Bot added impact: usability Core flow broken or severely blocked size/M 50–199 added + deleted lines (all files); change volume, not priority. labels Oct 28, 2026
@silo-triage silo-triage Bot removed the size/M 50–199 added + deleted lines (all files); change volume, not priority. label Oct 28, 2026
@silo-kody

silo-kody Bot commented Oct 28, 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 8a96bcf into Silo-Server:main Oct 31, 2026
24 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working evidence-required Needs before-and-after evidence before the Evidence check passes go Pull requests that update go code impact: usability Core flow broken or severely blocked priority: P2 Limited scope, workaround exists, or polish 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.

2 participants