Repository navigation
perf(scanner): finalise variants from narrow rows with batched writes - #2218
Conversation
Variant finalisation loaded every file in the scan scope with all columns, then looked up each scoped file's owner with its own GetByEpisodeID or GetByContentID query, so one pass over a 250k-file series root made about 250k queries even when nothing had changed. Each changed file went back through the full Upsert, which writes every column from the copy loaded at the start of the pass and clears match_suppressed_at and missing_since. - Read a narrow VariantFile row (id, owner, path and the edition, presentation and multi-episode columns) for present files only, using the range form of the path predicate so the folder/path index stays usable under a generic plan. - Parse each path once per pass. - Read the in-scope owners' other files in chunked owner queries: every file of an owner with a multipart group in the scope, and only the files stored as parts for the rest, so parts left behind by a renamed part still get a new total. - Write changes with UpdateVariantMetadata, which sets only the variant columns and updated_at in batches through unnest, with bigint ids, and skips rows that went missing, moved or already hold the values. The two query-budget tests are pinned in scripts/ci/db-pins.txt, and the two behaviour tests in scripts/ci/db-contracts.txt.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Silo Kody — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
|
Warning Review limit reachedYou've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Next included review available in 33 minutes. View limit details
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info
📝 Walkthrough
Merge Risk: ⚪ Minimal · up to
|
…scope When the stored-parts lookup turns up a part of a multipart group for an owner that was read only for its stored parts, read the rest of that owner's files too. Other parts of the group can be stored without part columns, as after a parser change, and the group's total needs every part; otherwise the stored part was totalled alone and written as 0. TestFinalizeVariantsReadsWholeGroupFoundOutsideTheScopeDB is listed in scripts/ci/db-contracts.txt.
Silo Kody — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
Problem
Related issue: #2087
Validation tasks: none recorded as passed on the board. The scan cases this path reaches, #1250 C1 and the #197 rescan case, are not run yet.
Every scan ends with a "Finalizing media variants" pass over each match scope. On a large series library that pass costs about as much as the rest of the scan, even when nothing changed. This change makes it read and write only the columns it uses, with a few chunked queries per scope instead of one query per file. Locally, an unchanged 253,501-file root goes from 65 s and 253,502 queries to 16 s and 52 queries.
On upstream
mainthe pass loads every file in the scope with all columns (GetByFolderAndPathPrefix). It then runsGetByEpisodeIDorGetByContentIDonce per scoped file to collect the owner's other files, decoding every row's track and chapter JSON. On my server, one full scan of my largest series library spent 5 min 15 s of its 11 min 24 s in this step, as #2087 describes.Each file whose variant metadata changed went back through the full
Upsert. That writes every column from the copy loaded at the start of the pass, so anything written to the row in the meantime is lost. It also setsmatch_suppressed_atandmissing_sinceto NULL. An owned file can carrymatch_suppressed_at: the backlog suppresses an unmatched file, andUpdateContentIDlinks it later without clearing the flag. Finalization cleared it whenever that file's parsed edition or parts changed.This leaves part of #2087 open: the pass still parses every file in the scope on every scan. That is now most of its cost (Benchmarks). Limiting it to files a scan touched needs change tracking from the scan, which is a separate change.
Approach
VariantFilerow: id, owner, path and the edition, presentation and multi-episode columns. It has no probe fields, so it can't be passed toUpsert.pathscope.RangeCoverageClauses), which keeps the folder/path index usable under a generic plan.UpdateVariantMetadatawrites changes in batches of 1,000 rows throughunnest. It sets only the variant columns andupdated_at, and skips rows that went missing, moved to another path or already hold the values. Ids arebigint, likemedia_files.id.One behaviour changes on purpose. A subtree scan used to re-finalize every file in the folder that shared an owner with a file in the scope. Now an out-of-scope file is re-finalized only when its owner has a multipart group in the scope, or when it is stored as a part. A file's other variant values come from its own path, so they only change when that file's scope is scanned, and a full library scan still covers every file.
Validation
go test ./internal/scanner/ -count=1without a database, andgo vet ./internal/scanner/: pass.go run ./scripts/ci/dbpins -list, against a migrated local PostgreSQL 18.6: pass.scripts/ci/db-pins.txt: a pass over a season costs one scope load, one owner lookup and one batched update, and a second pass writes nothing. A movie split across two discs, one outside the scope, gets a total of 2 on both in the same three queries.scripts/ci/db-contracts.txt,TestFinalizeVariantsKeepsMatchSuppressionDB: an unmatched movie file is suppressed, linked withUpdateContentIDand finalized. Its edition must change whilematch_suppressed_at, its probe and chapter columns and a missing sibling stay as they were. Its id is past the int4 range.scripts/ci/db-contracts.txt,TestFinalizeVariantsRetotalsPartsLeftByARenameDB: disc 2 of a two-disc movie is renamed, and a file scan finalizes only the new path. Disc 1's total must drop from 2 to 0.scripts/ci/db-contracts.txt,TestFinalizeVariantsReadsWholeGroupFoundOutsideTheScopeDB: disc 2 is stored without part columns and the scope holds another file of the movie. Both discs must end with a total of 2.main(bf63b3d22): the suppression test fails onfinalize cleared match_suppressed_at on the cut, and the other two pass. The rename test fails on a version that looks up owners only for multipart groups, as my fork does, and the whole-group test fails ondf14c62b6(disc 1 total 0). With the update's ids narrowed toint32, the suppression test fails on the edition, because the update misses the row.0d2fc9f12: every Go job passes, including Go DB pins, which runs the new variant DB tests, and the web checks and tests pass.Web (build), and with itCI result, fails only the launch bundle budget, by 1,214 B, the same failure as onmain([bug] Web build fails the launch bundle budget on main after #2168 #2203, fix in fix(web): keep the download storage API out of the launch bundle #2204). This pull request changes no web code.Benchmarks
Measured locally with a temporary harness (not committed). It calls
FinalizeVariantsByPathPrefixon a seeded library, counts statements with a pgx tracer and Go allocation withruntime.MemStats. Each scenario ran three times after one untimed pass that converges the stored values.mainbf63b3d22. After: this branchdf14c62b6.shared_buffers1 GB,work_mem32 MB, durability settings at their defaults), Go 1.27.1 withGOMAXPROCS=6andGOMEMLIMIT=3GiB.0d2fc9f12came after these runs. It adds a second owner lookup only when the stored-parts lookup turns up a multipart part, which this workload never does, and the query-count pins are unchanged. Both versions fixed all 20,000 stale rows in every repair run and gave both split parts a total of 2. The third repair run was slower for both versions. I didn't find a cause and left the numbers as measured. After the change, a whole-root pass makes one scope load and 51 owner lookups of up to 5,000 episodes each.A CPU profile of the after runs puts 88% of the samples in
naming.ParseVariantHints. What remains is mostly filename parsing on one goroutine.From my server, read-only. It runs my fork, which already batched the owner lookup into one query per scope, so its "before" was cheaper than upstream
main:Before (fork at
6ce7fb5cc, 7 October): the three finalizing phases of one full scan took 34 s, 50 s and 3 min 50 s for scopes of 11,564, 20,982 and 221,014 files.pg_stat_statements, one statistics window on the same server. Between 5 and 8 October the old wide owner lookup ran 722 times (mean 241 ms, maximum 37.9 s). From the 8 October deploy of the narrow pass to 10 October:That deployed build only looked up owners with multipart groups, so its lookups are fewer than this branch makes. These are database times only and leave out the decoding and parsing in Go.
I don't have per-phase scan timings from my server after the change. The logs of the scans since 8 October went with the containers those builds ran in.
Evidence
Evidence: none, no user-visible change. Finalization writes the same variant values as before for every file it processes. The benchmark output, the regression test runs and the production query statistics are on the evidence page.
Evidence: https://evidence.siloserver.org/r/silo-server/pr-2218/
Risks
mainhas the same gap.Checklist
AI Disclosure
mainfor value differences from the old code, SQL NULL handling and casts, convergence, concurrent writers, and whether the tests check what they claim. It found that when a part was renamed out of its group and the scope held only the new file, the remaining part kept a total of 2, which upstream's per-file lookup had fixed. The owner lookup now reads the stored parts of every in-scope owner, andTestFinalizeVariantsRetotalsPartsLeftByARenameDBcovers it. An earlier review pass found the update narrowingbigintids toint32, which is fixed and covered by the suppression test. The batched-lock point it raised is under Risks. Kody then found that a part read as a stored part could be totalled without group members stored without part columns. That is fixed in0d2fc9f12and covered byTestFinalizeVariantsReadsWholeGroupFoundOutsideTheScopeDB.AI-assisted with Claude Opus. I directed the task and designed the work.