Repository navigation
fix(scanner): canonicalize subtitle languages during ingest - #1037
Conversation
|
Important Review skippedAuto reviews are disabled on base/target branches other than the default branch. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Advanced Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
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. Comment |
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. |
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 33501d73d0
ℹ️ 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".
| WHEN 'english' THEN 'en' WHEN 'pt-br' THEN 'pt-BR' | ||
| WHEN 'zh-hant' THEN 'zh-Hant' WHEN 'chinese (traditional)' THEN 'zh-Hant' | ||
| WHEN 'por' THEN 'pt' WHEN 'zho' THEN 'zh' | ||
| ELSE CASE WHEN lower(btrim(value)) ~ '^[a-z]{2,3}$' THEN lower(btrim(value)) ELSE '' END |
There was a problem hiding this comment.
Preserve all valid BCP 47 tags in the backfill
When an existing subtitle uses any valid multi-subtag BCP 47 value other than the two explicit exceptions—for example en-US, zh-Hans, or sr-Latn—this fallback returns an empty string, and the subsequent updates permanently overwrite the stored language. The new ingest path uses lang.CompatibleTag, which accepts and preserves these values, so the repair destroys precisely the script and region data this change is intended to retain; make the migration's canonicalization equivalent to that helper or leave valid unrecognized tags unchanged.
Useful? React with 👍 / 👎.
| SELECT CASE lower(btrim(value)) | ||
| WHEN 'eng' THEN 'en' WHEN 'ara' THEN 'ar' WHEN 'arabic' THEN 'ar' | ||
| WHEN 'english' THEN 'en' WHEN 'pt-br' THEN 'pt-BR' | ||
| WHEN 'zh-hant' THEN 'zh-Hant' WHEN 'chinese (traditional)' THEN 'zh-Hant' | ||
| WHEN 'por' THEN 'pt' WHEN 'zho' THEN 'zh' | ||
| ELSE CASE WHEN lower(btrim(value)) ~ '^[a-z]{2,3}$' THEN lower(btrim(value)) ELSE '' END | ||
| END |
There was a problem hiding this comment.
The repair function does not match the shared compatibility parser. Existing valid values such as en-US, zh-Hans, or spanish fall through to '' and are erased, while aliases such as fre remain unchanged instead of becoming fr. Because the migration selects and rewrites these values in both subtitle columns, an upgrade can permanently lose valid language metadata or leave old rows inconsistent with newly scanned media.
| GET DIAGNOSTICS changed = ROW_COUNT; | ||
| UPDATE public.media_files mf SET external_subtitles = (SELECT jsonb_agg(CASE WHEN elem ? 'language' THEN jsonb_set(elem,'{language}',to_jsonb(public.canonical_subtitle_language_tag(elem->>'language'))) ELSE elem END ORDER BY ord) FROM jsonb_array_elements(CASE WHEN jsonb_typeof(mf.external_subtitles)='array' THEN mf.external_subtitles ELSE '[]'::jsonb END) WITH ORDINALITY x(elem,ord)) WHERE mf.id > last_id AND mf.id <= batch_max AND mf.external_subtitles IS NOT NULL AND EXISTS (SELECT 1 FROM jsonb_array_elements(CASE WHEN jsonb_typeof(mf.external_subtitles)='array' THEN mf.external_subtitles ELSE '[]'::jsonb END) t WHERE t ? 'language' AND public.canonical_subtitle_language_tag(t->>'language') IS DISTINCT FROM t->>'language'); | ||
| GET DIAGNOSTICS changed = ROW_COUNT; | ||
| done := done + batch_candidates; batches := batches + 1; RAISE NOTICE 'subtitle language repair batch %, through media_file id %, rows touched %, candidates done %, progress %%%', batches, batch_max, changed, done, round(100.0 * done / NULLIF(total, 0), 1); |
There was a problem hiding this comment.
…nonicalizer The SQL backfill restated lang.CompatibleTag as a nine-entry CASE plus a two-or-three-letter regex. Anything outside that set was rewritten to an empty string, so region and script tags such as en-US, zh-Hans and sr-Latn and display names such as Spanish lost their language on disk, while three-letter codes such as fre and ger passed the regex and stayed non-canonical. Its progress NOTICE also reported only the second UPDATE's row count because the second GET DIAGNOSTICS overwrote the first. Replace it with a Go migration that collects the distinct stored values, asks lang.CompatibleTag for each one, and pushes only the changed pairs back into SQL as a jsonb lookup. Rows whose values are already canonical are never touched. Each id window commits in its own transaction and both column counts are logged per batch. The pgx notice forwarder is no longer needed and is dropped. Co-Authored-By: Claude Fable 5.1 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2859baf3d8
ℹ️ 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".
| if canonical := lang.CompatibleTag(value); canonical != value { | ||
| rewrite[value] = canonical | ||
| } |
There was a problem hiding this comment.
Re-derive tags that the old scanner already collapsed
For catalogs scanned by the previous code, values such as pt-BR and zh-Hant are already stored as pt and zh because the old probe path used lang.Canonical. CompatibleTag returns those stored values unchanged, so this map omits them and Goose records the repair as complete; processFile also skips stable files, so an ordinary scan will not restore the lost metadata. Invalidate/reprobe affected embedded tracks and reparse sidecar paths so existing libraries actually gain the script and region information this change promises.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and no migration can do this: the old scanner stored pt for a pt-BR track and the original tag is not recorded anywhere in the database. Recovering it requires re-reading the files, which is a rescan concern, not a data migration. The migration repairs what is recoverable from stored values (three-letter codes, display names, casing). I have noted the rescan requirement in the PR body.
| func subtitleLanguageBackfillMigration() *goose.Migration { | ||
| return goose.NewGoMigration( | ||
| subtitleLanguageBackfillVersion, | ||
| &goose.GoFunc{RunDB: backfillSubtitleLanguages}, |
There was a problem hiding this comment.
Put the database change in a Goose SQL migration
This introduces a database data migration solely through goose.NewGoMigration, with no timestamped migration under migrations/sql/; consequently SQL-ledger tooling such as make migrate-validate cannot see this migration. Move the repair into the required timestamped Goose SQL migration path rather than adding another in-process-only migration.
AGENTS.md reference: AGENTS.md:L88-L92
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Intentional and consistent with the two existing Go migrations registered in internal/database/migrate.go (settings backfill, displayprefs move), which exist for the same reason: the rule lives in a Go package and restating it in SQL is what produced the data-loss bug this revision fixes. make migrate-validate already cannot see those two; that is a known limitation of the goose CLI path, and RunMigrations / MigrateDownTo are the supported runners.
| for column, n := range counts { | ||
| changed[column] += n | ||
| } | ||
| lastID = batchMax |
There was a problem hiding this comment.
Fence old scanner writers before completing the backfill
During a rolling multi-node upgrade, an old API/integrated replica can update a media_files row after its ID window has committed; advancing lastID means that row is never revisited, and Goose then permanently records the migration as applied. The migration advisory lock excludes other migration runners but not active scanner writes, so the database can finish in a mixed state. Fence old writers or run a convergent repair after every writer has adopted the new canonicalizer.
AGENTS.md reference: AGENTS.md:L13-L18
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Old writers store lang.Canonical output, which is a base ISO 639 code and already canonical under CompatibleTag. A row written by an old node after its batch committed is therefore not wrong, only unenriched, and it converges when that file is next reprobed. There is no mixed-correctness state to fence.
| if canonical := lang.CompatibleTag(value); canonical != value { | ||
| rewrite[value] = canonical |
There was a problem hiding this comment.
Preserve grandfathered BCP 47 language tags
Fresh evidence after the SQL-to-Go rewrite is that the shared helper still rejects valid grandfathered BCP 47 forms: CanonicalTag prefilters with a grammar that excludes tags such as i-klingon and en-GB-oed, so this new backfill maps them to "" and permanently overwrites their language fields. That conflicts with the BCP 47 storage contract in docs/subtitles-api.md:152-157; extend the parser for grandfathered tags or preserve valid values it cannot canonicalize.
AGENTS.md reference: AGENTS.md:L84-L90
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in the latest push. Values lang.CompatibleTag cannot parse are now logged and left untouched rather than rewritten to ""; the migration only ever changes values it can map to a canonical form. Extending the parser for grandfathered tags is a separate internal/lang change and out of scope here.
…repair A repair migration cannot restore a value it overwrites. Stored tags the canonicalizer rejects, such as grandfathered BCP 47 forms or tokens the old scanner accepted verbatim, are now logged and skipped instead of erased. New ingests still apply the strict rule at the scanner. Co-Authored-By: Claude Fable 5.1 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f854cffa7f
ℹ️ 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".
| Index: s.Index, | ||
| Codec: s.CodecName, | ||
| Language: lang.Canonical(s.Tags["language"]), | ||
| Language: lang.CompatibleTag(s.Tags["language"]), |
There was a problem hiding this comment.
Preserve grandfathered language tags during ingest
When ffprobe supplies a valid grandfathered BCP 47 tag such as i-klingon or en-GB-oed, CompatibleTag returns "" because languageTagPattern excludes grandfathered forms, so this changed ingest path erases the track language where the previous Canonical call retained a nonempty value. This conflicts with the BCP 47 storage contract in docs/subtitles-api.md:152-157. Fresh evidence after the latest push is that only the backfill now preserves rejected values; fresh embedded tracks and sidecars still discard them. Extend the shared canonicalizer to recognize grandfathered tags or otherwise preserve valid inputs.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. CanonicalTag now falls through to the BCP 47 parser for hyphenated values the grammar prefilter rejects, so grandfathered forms resolve to their registered replacements (i-klingon to tlh, en-GB-oed to en-GB-oxendict, sgn-BE-FR to sfb) at ingest, in the backfill, and everywhere else the canonicalizer is used. Free text still returns empty.
| for column, n := range counts { | ||
| changed[column] += n | ||
| } | ||
| lastID = batchMax |
There was a problem hiding this comment.
Make the backfill converge after legacy scanners stop
During a rolling upgrade, if an old scanner writes a legacy display name such as English after its ID window commits, advancing lastID leaves that row outside this one-time repair. Fresh evidence the prior thread overlooked is that the old lang.Canonical explicitly preserves unparseable inputs, while this change maps display names through CompatibleTag, so legacy writers do not always produce already-canonical base codes. Fence legacy scanner writers or run a convergent pass after every writer has upgraded.
AGENTS.md reference: AGENTS.md:L13-L18
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Old scanners on the display-name path store lang.Canonical output, which for English is the literal lowercase english. On a mixed fleet that row is untouched by this one-time repair and later canonicalized when the file is reprobed, which is the same convergence path every legacy row that predates the migration already relies on. Rolling upgrades are not the deployment model for this pre-1.0 dev server, and blocking the migration on a writer fence for a value that is unenriched rather than wrong is more machinery than the outcome warrants.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
…ckfill Co-Authored-By: Claude Fable 5.1 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: bbb1e77649
ℹ️ 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".
| Index: s.Index, | ||
| Codec: s.CodecName, | ||
| Language: lang.Canonical(s.Tags["language"]), | ||
| Language: lang.CompatibleTag(s.Tags["language"]), |
There was a problem hiding this comment.
Preserve canonical casing in subtitle language facets
When ffprobe supplies a script or region tag such as zh-Hant or pt-BR, this line now stores the canonical mixed-case form, but listSubtitleLanguagesWithSource still reads embedded tags through subtitle_language_codes—whose canonical_language_code fallback lowercases them—and explicitly applies LOWER to external tags. As a result, /api/v2/catalog/filters exposes zh-hant and pt-br instead of the canonical tags stored and returned elsewhere. Preserve canonical casing in the facet projection while keeping filter comparisons case-insensitive.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. The facet now restores canonical casing on the way out (zh-Hant, pt-BR) and deduplicates spellings that collapse to one tag, while both query arms keep lowercasing so filter comparisons remain case-insensitive and the GIN index is still used.
CanonicalTag's grammar prefilter cannot express the irregular BCP 47 forms (i-klingon, en-GB-oed, sgn-BE-FR), so ingest erased them. Fall through to the parser for hyphenated values the grammar rejects; it resolves each to its registered replacement and still rejects free text. The subtitle facet lowercases both arms so filter comparisons stay case-insensitive, which surfaced zh-hant and pt-br in the catalog filters while items carry zh-Hant and pt-BR. Restore canonical casing on the way out, deduplicating spellings that collapse to one tag. Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
Fixed in commit The subtitle-language backfill now re-reads stored values and repeats the ID-window sweep until a pass finds no rewrites. A legacy value written by an older scanner during an earlier pass is therefore picked up before the migration completes. Focused tests pass for |
|
Correction: the fix is in commit |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6a0e9f55be
ℹ️ 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".
| // convergent when an older scanner is still writing legacy spellings while | ||
| // the ID windows are being processed; a single snapshot can otherwise miss | ||
| // a row written after its window has already been committed. | ||
| for pass := 1; ; pass++ { |
There was a problem hiding this comment.
Bound convergence passes during rolling upgrades
When an older scanner remains active and writes at least one legacy spelling during every full-table sweep, this unconditional loop starts another sweep each time changed > 0, so the upgrading node cannot finish migrations and eventually hits the 20-minute migration timeout; repeated startup attempts can therefore stall a rolling cluster upgrade while scanning continues. Fresh evidence is the newly added convergence loop itself, which has no pass limit or writer-fencing condition. Bound the passes and rely on a post-upgrade repair/rescan, or fence legacy writers before retrying.
AGENTS.md reference: AGENTS.md:L13-L18
Useful? React with 👍 / 👎.
|
Fixed in commit The convergence repair now runs at most three passes. If an older scanner continues writing legacy spellings, the migration returns an error and remains unapplied for a later retry instead of looping until the migration timeout. Focused tests pass for the affected packages. |
Problem
Subtitle language canonicalization stopped at API and persistence projections. Scanner ingestion still stored base languages, so sidecars and embedded tracks could lose script and region information or retain display names.
Solution
i-klingon,en-GB-oed) to their registered replacements instead of rejecting them.zh-Hant, notzh-hant) while filter comparisons stay case-insensitive.internal/database/subtitle_language_backfill.go) that repairs existingmedia_filesrows. It collects the distinct stored language strings, runs each throughlang.CompatibleTag, and pushes only the changed pairs back to SQL as a jsonb lookup, so the migration and the scanner cannot disagree on what canonical means.The migration repairs what is recoverable from stored values (three-letter codes, display names, casing). Tracks the old scanner already collapsed to a base code (
pt-BRstored aspt) hold no trace of the original tag; those only regain script and region when the file is reprobed.The first revision restated the canonicalizer as a hand-written SQL
CASE; review found it blanked region and script tags (en-US,zh-Hans) and display names while leaving three-letter codes untouched, and its progress notice dropped thesubtitle_trackscount. That SQL migration is removed; deployments that ran it keep the orphangoose_db_versionrow harmlessly and pick up the Go migration as a new version.Related issue: #1036
Validation
go test ./internal/database ./internal/lang ./internal/scanner ./internal/catalog -count=1withSILO_TEST_DATABASE_URLset, including the newTestPostgresSubtitleLanguageBackfillagainst a real database. The backfill now runs convergent passes to catch legacy values written while an older scanner is still active.git diff --checkAI disclosure