Skip to content

fix(intromarkers): stop re-refining unchanged silence backfill files - #1342

Merged
Quick104 merged 5 commits into
mainfrom
fix/issue-1272-silence-backfill-attempts
Sep 24, 2026
Merged

Quick104 merged 5 commits into
mainfrom
fix/issue-1272-silence-backfill-attempts

Conversation

@Quick104

@Quick104 Quick104 commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Related issue: #1272
Validation tasks: none

The marker job's chapter silence backfill refines up to 2,000 scanner chapter:v1 intro markers per run, oldest intro_markers_detected_at first. When a refinement finds no better intro end, or ffmpeg fails, the marker write is a no-op and intro_markers_detected_at stays the same, so those files sort first again on the next run. On a development deployment with about 54,000 chapter:v1 markers, each of the six nightly runs I checked filled its 2,000-file budget, yet the front of the queue still held files detected on 2026-08-08. The other ~51,800 were never reached.

Approach

A new table, intro_silence_refinement_attempts, keeps one row per file whose last refinement kept the chapter boundary. It stores the file hash, size and duration, a SHA-256 of the file's chapters as loaded for the refinement, the intro range that was refined, a hash of the silence settings (Config.SilenceConfigHash), the status (no_improvement or failed), the host that recorded it, the failure count and retry_after.

  • Analyzer.refineChapterSegment records the outcome whenever a refinement does not apply, in both the first chapter pass and the backfill. A cancelled run records nothing.
  • The backfill skips a file while its row matches the file's current identity, chapters, marker range and settings. The chapters hash matters because the refined segment comes from the chapters, and a re-probe can rewrite them without touching the file identity or the stored marker. A no_improvement result stands until one of those changes. A failure is retried after 12 hours, doubling per consecutive failure up to 7 days. Scheduled tasks run on every server, each with its own ffmpeg and media mounts, so a failure only defers retries on the server that recorded it, and backoff escalates only on that server's own failures after its previous retry_after passed. A forced episode analysis that fails inside the window keeps the existing schedule. Files never attempted sort first, then the oldest attempts.

intro_markers_detected_at can't hold this state: the marker write path ignores it for unchanged markers on purpose, to avoid audit noise. A separate table matches how Chromaprint season analysis already caches complete and not_found results.

The attempt lookup is a LEFT JOIN for a planner reason. The planner estimates the candidate filter at a handful of rows. Written as NOT EXISTS, it chose a nested-loop anti-join that rescans the attempts table for every candidate (about 20 s with 2,000 attempt rows, growing with the table). A per-row subquery avoided that but lost the parallel scan (37 s). The LEFT JOIN probes the primary key per file inside the parallel scan: 2.4 s on that deployment, against 6.3 s for the current query under the same load. baseCandidateSelect is split into its select/from and where parts so this query can add the join; the other queries are unchanged.

Migration 20260923000630 creates the table and sorts before main's 20260923181331; the runner allows out-of-order versions. 20260923203213 adds chapters_hash and recorded_by and widens media_file_id to bigint (a no-op on fresh databases, where the table migration already creates it as bigint). It is a separate migration because a development deployment had already applied the first version of the table migration with an integer column. Existing rows get an empty hash, which never matches, so those files are refined once more.

Validation

  • Unit tests with the fake repository cover no-improvement and failure recording, the backoff sequence, a failure inside the backoff window not escalating it, another server's failure not escalating it, the failure count resetting when inputs (including chapters) change, no record on cancellation or when the refinement applies, and the settings hash scope.
  • TestSilenceBackfillSkipsUnchangedAttemptsPostgres runs the backfill twice against Postgres: the second run skips both recorded files, and a settings change, an elapsed retry time, rewritten chapters and a moved marker each make a file eligible again, and a file inside one server's backoff stays eligible for another server. One fixture file has an ID above the int32 range. It also confirms that the Go and SQL chapters hashes agree. It fails without the skip clause. It needs SILO_TEST_DATABASE_URL, which CI does not set for this package; I ran it locally against a fresh database, which the test migrates.
  • Both migrations down and up on a fresh database, and an upgrade from the integer column (rows and foreign key kept).
  • Development deployment (first commit, before the chapters hash and the per-server failure rules): I deployed the branch and ran the marker job once. The backfill considered 2,000 files, with 0 refinement errors and 161 improvements applied (9–92 per night before). All 2,000 files from the stuck batch now have a no_improvement row whose range matches the current marker. The next batch is 2,000 different files, none recorded yet, starting where the old batch ended.
  • go build ./..., gofmt, go vet ./..., make lint-changed, make migrate-validate and scripts/check-local-path-leaks.sh pass.
  • make test-go on macOS: every package passes except internal/apiv2, where TestAdminResourceCapabilitiesAndScope fails because cgroup resources report unsupported on macOS. It fails the same way on main.
  • The web client is unchanged; web checks were not run.

Risks

  • The migrations add one empty table with a foreign key to media_files (ON DELETE CASCADE), then two columns and a bigint widening on it. No existing media_files rows are rewritten.
  • The first run after deploy refines the current batch once more to record it. After that, unchanged files stay skipped.
  • A failure that hits every file on a server for several nights (ffmpeg missing, for example) pushes those files back on that server by up to 7 days after the cause is fixed. Other servers still process them.
  • A file that fails on every server (corrupt audio, for example) is retried by each server on each run instead of backing off, because the servers overwrite each other's failure rows. Those files sort after never-attempted files.
  • The settings hash does not cover the refiner's code. A change to RefineChapterEnd that should re-run recorded files needs a ChapterSilenceAlgorithm bump; a code comment says so.
  • A backfill file whose chapters no longer contain an intro is never recorded and still takes a slot in each batch, without an ffmpeg run. This PR does not change that.

No API, client or jellycompat change.

Checklist

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

AI Disclosure

  • Harness: Claude Code, running in T3 Code
  • Tool(s): Claude Code built-in tools (shell, file read/edit, subagents), GitHub CLI (gh)
  • Model(s): claude-opus-5-5[1m] for the main session; claude-opus-5-5 for the review subagent
  • Involvement: Fully AI-generated; maintainer review pending
  • Adversarial review: A separate reviewer subagent (pr-review-toolkit:code-reviewer, claude-opus-5-5) read the full diff and the code it depends on (the scanner marker write path, CanWriteMarkerUpdate, the media_files_invalidate_markers trigger, the silence refiner). It checked skip and retry semantics, float and NULL comparisons, races between candidate load, attempt record and marker write, the trigger interaction and migration safety. It found no correctness bugs. It flagged that the Postgres test assumed an already-migrated database (fixed: the test now runs migrations) and suggested documenting that the settings hash does not cover the refiner's code (comment added). The query moved from NOT EXISTS to LEFT JOIN after that review, based on plans measured on the development deployment; the Postgres test covers the final form. After opening, Codex review flagged that duplicate runs across servers could multiply the failure backoff; fixed in dfa1f0f. A second pass flagged that a chapters-only change left the skip in place; fixed in 49f3435. A third flagged that one server's local failure deferred the file on healthy servers; fixed in 958c6ae. A fourth flagged the integer file ID after the core ID widening; fixed in ec697f6.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Improvements
    • Intro silence refinement now avoids repeatedly processing files when it finds no improvement, and retries failed refinements with increasing delays.
    • Refinements can be reconsidered when relevant audio, chapter markers, or settings change. Retry timing is coordinated across servers to reduce unnecessary repeat attempts.

A chapter silence refinement that finds no better intro end, or fails,
leaves the chapter:v1 marker unchanged, so intro_markers_detected_at never
moves and the backfill picks the same files ahead of everything else on
every run.

Record each such attempt in intro_silence_refinement_attempts with the file
identity, the refined range, and a hash of the silence settings. The backfill
skips a file while its attempt still matches: until the inputs change after a
clean no-improvement result, and until retry_after (12h doubling, capped at
7 days) after a failure. Files never attempted are picked first.

Fixes #1272

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

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

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-23T20:59:58.714926Z ec697f6 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.

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

@coderabbitai

coderabbitai Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Advanced

Run ID: f8d07c01-b0f3-4a38-a811-bc2bf9a2f744

📥 Commits

Reviewing files that changed from the base of the PR and between 61fe4e0 and ec697f6.

📒 Files selected for processing (7)
  • internal/intromarkers/analyzer.go
  • internal/intromarkers/analyzer_test.go
  • internal/intromarkers/repository.go
  • internal/intromarkers/silence_backfill_db_test.go
  • internal/intromarkers/types.go
  • migrations/sql/20260923000630_add_intro_silence_refinement_attempts.sql
  • migrations/sql/20260923203213_scope_intro_silence_refinement_attempts.sql

Included review availability: Your plan provides up to 2 included reviews per hour; 0 remain after this review.


📝 Walkthrough

Walkthrough

The silence backfill now stores refinement outcomes and uses configuration, file, chapter, and intro inputs to identify unchanged attempts. Candidate selection skips matching no-improvement attempts and defers matching failures during node-specific retry windows.

Changes

Silence refinement backfill

Layer / File(s) Summary
Attempt contract and candidate storage
internal/intromarkers/types.go, internal/intromarkers/repository.go, migrations/sql/*intro_silence_refinement_attempts.sql
The attempt record stores refinement inputs, outcomes, and retry data. Repository queries load and update attempts, hash chapter data, and filter candidates using matching inputs and retry state. Migrations add the attempt table and its chapter hash, node identity, and bigint file ID.
Analyzer recording and retry handling
internal/intromarkers/analyzer.go
The analyzer records no-improvement results and non-canceled failures. Failure retries use exponential backoff, and candidate queries receive the configuration and node identity.
Backfill eligibility validation
internal/intromarkers/analyzer_test.go, internal/intromarkers/silence_backfill_db_test.go
Unit and PostgreSQL tests cover attempt recording, retry timing, changed inputs, cancellation, node-specific behavior, and candidate selection.

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

Sequence Diagram(s)

sequenceDiagram
  participant Analyzer
  participant Repository
  participant BoundaryRefiner
  Analyzer->>Repository: List candidates with config and node identity
  Analyzer->>BoundaryRefiner: Refine chapter boundary
  BoundaryRefiner-->>Analyzer: Return result or error
  Analyzer->>Repository: Load prior attempt
  Analyzer->>Repository: Upsert refinement attempt
Loading

Merge Risk: ⚪ Minimal · up to ec697

Chapter-silence backfill now remembers files whose refinement made no difference or failed, so later runs stop reprocessing them. Files become eligible again when settings, chapters, file identity, or intro markers change, and failures retry with bounded backoff. No outstanding defect remains after review, and the change looks ready to merge.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 26.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 15 functions across 5 files. (2 skipped: … Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: preventing repeated refinement of unchanged silence backfill files.
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: Docstring Coverage

Explanation

Docstring coverage is 26.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 15 functions across 5 files. (2 skipped: 2 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@chatgpt-codex-connector chatgpt-codex-connector Bot 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: 72d05da543

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

Comment thread internal/intromarkers/analyzer.go Resolved
… window

Scheduled tasks run per process, so every API server runs the nightly
marker job over the same files. A failure recorded while an earlier failure
is still backing off is a duplicate run (or a forced episode analysis), not
a retry, and no longer escalates the failure count or moves retry_after.

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

@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: dfa1f0fe87

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

Comment thread internal/intromarkers/repository.go Resolved
The refined intro segment comes from the file's chapters, and a re-probe
can rewrite them without changing the file identity or the stored marker.
Record a SHA-256 of the chapters loaded with the candidate and require it
to match mf.chapters before skipping a file.

The column lands in its own migration because a development deployment
already applied the table migration. Existing rows get an empty hash, so
those files are refined once more.

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

@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: 49f3435b55

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

Comment thread internal/intromarkers/repository.go Resolved
… server

Every server runs the nightly marker job against its own ffmpeg and media
mounts. A failure recorded by one server (missing ffmpeg, lost mount) no
longer defers the file on other servers: the attempt records the host that
wrote it, the backfill honors retry_after only for its own failures, and
backoff escalates only on the same server. No-improvement results still
apply everywhere.

The unapplied follow-up migration now adds recorded_by next to
chapters_hash and is renamed to cover both.

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

@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: 958c6ae556

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

media_files.id is bigint, so an int4 media_file_id would reject attempts
for files past the int32 range and leave them in the backfill loop. The
table migration now creates the column as bigint, and the follow-up
migration widens it on a database that already applied the integer
version.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
@Quick104
Quick104 merged commit 996b41f into main Sep 24, 2026
11 checks passed
@Quick104
Quick104 deleted the fix/issue-1272-silence-backfill-attempts branch September 24, 2026 00:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant