Skip to content

Page translation: Update installed language packs when the manifest changes their version - #10953

Merged
0nko merged 5 commits into
developfrom
feature/ondrej/page-translate-update-pack
Dec 4, 2026
Merged

0nko merged 5 commits into
developfrom
feature/ondrej/page-translate-update-pack

Conversation

@0nko

@0nko 0nko commented Dec 3, 2026 •

Copy link
Copy Markdown
Member

Task/Issue URL: https://app.asana.com/1/137249556945/project/1207418217763355/task/1220716832050752?focus=true
Tech Design: https://app.asana.com/1/137249556945/project/1207418217763355/task/1220682435514957?focus=true
Evidence URL: https://artifacts.go.duckduckgo.com/view/auto/32d0fd9d-05ca-4988-bd91-fc0b332b566e/20261203-172523-page_translation_pack_update-446c/index.html

Why

A downloaded language pack stays on the version it was installed with, so a model fix or a rollback in the manifest never reaches people who already have the pack. This PR replaces an installed pack in the background when the manifest lists a different version for its pair.

What changed

  • After each manifest fetch, LanguagePackScheduler.updateOutdated queues an update for every installed pack whose saved version differs from the manifest's. Each update goes into the pair's existing work chain, so it runs in order with that pair's downloads and deletes.
  • LanguagePackUpdateWorker downloads and checks the new pack, then swaps it in through TranslationEngine.replacePack. That waits until the pair's translator is unloaded, so a pack is never replaced while in use.
  • The installer's final move became a callback (moveIntoPlace). Downloads rename the pack into place, and updates swap it.

Scope

  • Covers installed packs only, and the update runs only on an unmetered network. On a metered network it's skipped, and the next manifest fetch (next app start) queues it again.
  • The update checks both the pageTranslation parent flag and its translation sub-flag.
  • Leaves out a progress UI. Updates are silent.

Tradeoffs

  • The update has no WorkManager network constraint. Updates share a chain with the pair's other operations, so an UNMETERED constraint would hold a delete or a corrupted-pack removal behind it until Wi-Fi. The worker checks the network itself instead.
  • The old pack moves to its own .replaced directory during the swap, not to .old. Startup cleanup deletes .old, which would lose the pack if the process died between the two renames. The rerun worker restores .replaced instead.
  • Deferred: the swap waits for the translator to unload after the download, with no time limit. If WorkManager stops the worker during that wait, the next attempt downloads the pack again. The update also doesn't stop mid-download when the flags turn off, and it doesn't check the manifest version again after that wait.

Blast Radius

This only touches people who already downloaded a pack, and only when the manifest changes a pair's version. A failed update keeps the installed pack and gives up after three attempts without failing the pair's later operations.

Verification

Checks

An installed language pack whose saved version differs from the manifest's is replaced in the background after the next manifest fetch, translation still works with the new pack, and nothing is updated while the parent pageTranslation flag is off.

Verified: An installed language pack whose saved version differs from the manifest's is replaced in the background after the next manifest fetch, translation still works with the new pack, and nothing is updated while the parent pageTranslation flag is off. Driven through the app's UI on a sdk_gphone64_arm64 (API 36).

This branch
flags-on This branch: flags-on
parent-off This branch: parent-off
parent-on This branch: parent-on
translated-with-updated-pack This branch: translated-with-updated-pack
video This branch: video

▶ Watch video · ▶ Watch video (part 2)

Key frames: This branch: key frames.

Outcome: Passes on this branch. All 10 checks passed.

Details: prove.py, proof written for this change (source below), builds this branch (c57d10ad70), sdk_gphone64_arm64, API 36, live services: DuckDuckGo translation models CDN, es.wikipedia.org. Full report

Unverified: Swap while a translator of the pair is loaded (replacePack waiting for the translator to unload is covered by RealTranslationEngineTest; a device run cannot time it reliably.); Skipping the update on a metered network (The emulator network is unmetered; LanguagePackUpdateWorkerTest covers the metered skip.); Restoring a pack after a process death mid-swap (The window is two renames; LanguagePackUpdateWorkerTest covers the restore.).

All checks
Check Result
Spanish pack installed through the download sheet pass (3.0)
Pack marked outdated with a marker file in it pass ({'sourceLanguage': 'es', 'targetLanguage': 'en', 'version': '0.0.1-outdated', 'architecture': 'base-memory', 'totalBytes': 25078663, 'files': {'lexicalShortlist': {'path': 'es-en/3.0/base-memory/lex.50.50.esen.s2t.bin.zst', 'bytes': 1880457, 'sha256': '5c3aae52d8fddeb2e09098171cdecf059ea453474633edcebc77375b04cbcaee', 'decompressedSize': 4636248, 'decompressedHash': 'e2610211d3b9577d012638fe7e7e74ed7b4b708ce96b9e792e67c282a6492daa'}, 'model': {'path': 'es-en/3.0/base-memory/model.esen.intgemm.alphas.bin.zst', 'bytes': 22849210, 'sha256': '7d1a512f3d3c420a0d87e52dccf6c83bf7eba7f4c54608824d3f86b757993a3e', 'decompressedSize': 31561787, 'decompressedHash': '4aed7734152ae0045d1a69ae49c86cfda18f53c61f90e95e1d1de1c7c7c3b033'}, 'vocab': {'path': 'es-en/3.0/base-memory/vocab.esen.spm.zst', 'bytes': 348996, 'sha256': '76b9ef220b22cec379f097852ca6312cabf065d5ddfb05149d5af31aa050ec22', 'decompressedSize': 816054, 'decompressedHash': '5ae254fa9b15aa182e70fd2a6186b1333c63a29a48043a9224c6aa4fcac058ad'}}})
Parent off: no update work queued pass (set())
Parent off: outdated pack left in place pass (0.0.1-outdated)
Outdated pack replaced with the manifest version after the manifest fetch pass ('3.0', expected '3.0')
Pack directory swapped for the new download (marker gone) pass
Update work ran and succeeded pass ([('bb063304-11cc-45bf-860e-dbfc1f25f46c', 2)])
No staging or old directory left behind pass (es-en )
No download sheet with the updated pack installed pass
Page translated with the updated pack pass (before: 'Miguel de Cervantes Saavedra (Alcalá de Henares, bautizado el 9 de octubre de 15' after: 'Miguel de Cervantes Saavedra (October 9, 1547 – April 22, 1616)[3] was a Spanish')
Proof source
"""An installed language pack whose saved version differs from the manifest's is replaced in the background after the next manifest fetch, translation still works with the new pack, and nothing is updated while the parent pageTranslation flag is off."""
import json
import sqlite3
import subprocess
import sys
import tempfile
import time
from pathlib import Path
sys.path.insert(0, str(Path.cwd() / '.agents/skills/verify-android/proofs'))
import steps
from prove import Error, verify

LIVE = ['DuckDuckGo translation models CDN', 'es.wikipedia.org']
PKG = 'com.duckduckgo.mobile.android.debug'
ES = 'https://es.wikipedia.org/wiki/Miguel_de_Cervantes'
PACK = 'files/page-translation/packs/es-en'
ENTRY = PACK + '/manifest-entry.json'
MARKER = PACK + '/stale-marker'
FAKE_VERSION = '0.0.1-outdated'
LEAD = "(() => { const p = document.querySelector('#mw-content-text p:not(.mw-empty-elt)'); return p ? p.innerText.slice(0, 80) : null })()"



def open_menu(android):
    for button in ('id:browserMenuImageView', 'id:browserMenu', 'id:inputModeWidgetNavMenu'):
        try:
            android.tap(button)
        except Error:
            continue
        if android.wait('text:Refresh', 5):
            return
    raise Error("the browser menu didn't open")


def sh(android, *args, stdin=None):
    return subprocess.run(['adb', '-s', android.serial, *args], input=stdin, capture_output=True)


def entry(android):
    p = sh(android, 'exec-out', 'run-as', PKG, 'cat', ENTRY)
    try:
        return json.loads(p.stdout)
    except ValueError:
        return None


def version(android):
    return (entry(android) or {}).get('version')


def make_outdated(android):
    data = entry(android)
    data['version'] = FAKE_VERSION
    sh(android, 'exec-in', 'run-as', PKG, 'sh', '-c', f'cat > {ENTRY}', stdin=json.dumps(data).encode())
    sh(android, 'shell', 'run-as', PKG, 'touch', MARKER)
    return version(android) == FAKE_VERSION and has_marker(android)


def has_marker(android):
    return sh(android, 'shell', 'run-as', PKG, 'ls', MARKER).returncode == 0


def update_work(android):
    with tempfile.TemporaryDirectory() as directory:
        for suffix in ('', '-wal'):
            p = sh(android, 'exec-out', 'run-as', PKG, 'cat', 'no_backup/androidx.work.workdb' + suffix)
            if p.returncode == 0:
                Path(directory, 'workdb' + suffix).write_bytes(p.stdout)
        with sqlite3.connect(str(Path(directory, 'workdb'))) as db:
            return db.execute("SELECT id, state FROM workspec WHERE worker_class_name LIKE '%LanguagePackUpdateWorker'").fetchall()


def translate_via_menu(android):
    android.open(ES)
    android.poll(lambda: android.web_eval('location.host'), lambda h: h == 'es.wikipedia.org', 30)
    original = android.poll(lambda: android.web_eval(LEAD), bool, 20)
    for _ in range(3):
        open_menu(android)
        for _ in range(3):
            if android.wait('text~:Translate Page to', 3):
                android.tap('text~:Translate Page to')
                return original
            android.scroll('up')
        verify('key', 'back')
        time.sleep(3)
    raise Error('the menu has no Translate Page row')
    return original


def set_flags(android, shot, **wanted):
    steps.settings(android)
    for _ in range(6):
        if android.visible('text:Feature Flag Inventory'):
            break
        android.scroll('up')
    android.tap('text:Feature Flag Inventory')
    android.wait('id:internal_edit_text', 10)
    android.type('id:internal_edit_text', 'pageTranslation')
    android._adb('shell', 'input', 'keyevent', '111')
    android.wait('text:pageTranslation', 10)
    time.sleep(1)
    state = lambda name: next(v for k, v in android.rows('primaryText', 'trailingSwitch').items() if k.split()[-1] == name)
    for name, on in wanted.items():
        for _ in range(3):
            index, checked = state(name)
            if bool(checked) == on:
                break
            android.tap('id:trailingSwitch', index=int(index))
            time.sleep(1)
        if bool(state(name)[1]) != on:
            raise Error(f'{name} switch did not turn {"on" if on else "off"}')
    android.shot(shot)
    verify('restart')
    settle(android)


def set_parent(android, on):
    set_flags(android, 'parent-on' if on else 'parent-off', pageTranslation=on)


def settle(android):
    android.poll(lambda: android.where(), lambda w: w in ('CookiePopupOptInActivity', 'BrowserActivity'), 10)
    time.sleep(2)
    steps.dismiss_cookie_prompt(android)


def run(android):
    android.reset()
    steps.dismiss_cookie_prompt(android)
    set_flags(android, 'flags-on', pageTranslation=True, translation=True)
    # the manifest fetch runs on start once translation is on; no manifest means no offer
    android.poll(lambda: android._adb('shell', 'run-as', PKG, 'ls', 'files/page-translation'), lambda o: 'models' in (o or ''), 60, interval=3)
    # the offer reads the cached manifest from a fresh start
    verify('restart')
    settle(android)
    steps.web_debugging_on(android)

    # install the pack the way a user does
    translate_via_menu(android)
    if android.wait('id:languagePackSheetButton', 15):
        android.tap('id:languagePackSheetButton')
    installed = android.poll(lambda: version(android), bool, 120, interval=3)
    android.check('Spanish pack installed through the download sheet', bool(installed), str(installed))
    if not installed:
        return
    android.note(f'installed version: {installed}')

    # parent flag off: the manifest still refreshes on start, but no update may be queued
    android.check('Pack marked outdated with a marker file in it', make_outdated(android), str(entry(android)))
    before = set(update_work(android))
    set_parent(android, False)
    time.sleep(25)
    added = set(update_work(android)) - before
    android.check('Parent off: no update work queued', not added, str(added))
    android.check('Parent off: outdated pack left in place', version(android) == FAKE_VERSION and has_marker(android), str(version(android)))

    # parent on: the next start's manifest fetch replaces the pack
    set_parent(android, True)
    android.mark()
    updated = android.poll(lambda: version(android), lambda v: v == installed, 180, interval=3)
    android.check('Outdated pack replaced with the manifest version after the manifest fetch', updated == installed, f'{updated!r}, expected {installed!r}')
    android.check('Pack directory swapped for the new download (marker gone)', not has_marker(android), '')
    android.check('Update work ran and succeeded', any(state == 2 for _, state in update_work(android)), str(update_work(android)))
    android.check('No staging or old directory left behind', sh(android, 'shell', 'run-as', PKG, 'ls', 'files/page-translation/packs').stdout.decode().split() == ['es-en'],
                  sh(android, 'shell', 'run-as', PKG, 'ls', 'files/page-translation/packs').stdout.decode())

    # translation still works on the updated pack, with no download sheet
    original = translate_via_menu(android)
    android.check('No download sheet with the updated pack installed', not android.wait('id:languagePackSheetButton', 4), '')
    translated = android.poll(lambda: android.web_eval(LEAD), lambda t: bool(t) and t != original, 240, interval=3)
    android.shot('translated-with-updated-pack')
    android.check('Page translated with the updated pack', bool(translated) and translated != original, f'before: {original!r}\nafter: {translated!r}')

    android.unverified('Swap while a translator of the pair is loaded', 'replacePack waiting for the translator to unload is covered by RealTranslationEngineTest; a device run cannot time it reliably.')
    android.unverified('Skipping the update on a metered network', 'The emulator network is unmetered; LanguagePackUpdateWorkerTest covers the metered skip.')
    android.unverified('Restoring a pack after a process death mid-swap', 'The window is two renames; LanguagePackUpdateWorkerTest covers the restore.')
Rerun
# save the proof source above as .agents/skills/verify-android/proofs/page_translation_pack_update.py
V=.agents/skills/verify-android/verify.sh
P=.agents/skills/verify-android/prove.py
$V build && $V install && $P .agents/skills/verify-android/proofs/page_translation_pack_update.py

Unit tests

Verified: ./gradlew :page-translation-impl:testDebugUnitTest passes on c57d10ad70. The tests cover the metered skip, restoring a pack after an interrupted swap, keeping the installed pack when the swap fails, the parent flag, and the swap waiting for the translator to unload.

Steps to test
  • Install the internal debug build. In Settings > Feature Flag Inventory, turn on pageTranslation and translation, then restart the app.
  • Open https://es.wikipedia.org/wiki/Miguel_de_Cervantes and use Translate Page to English to download the Spanish pack.
  • Mark the pack outdated so the next manifest fetch updates it:
    adb shell run-as com.duckduckgo.mobile.android.debug sed -i 's/"version":"[^"]*"/"version":"0"/' files/page-translation/packs/es-en/manifest-entry.json
    
  • Force-stop and reopen the app on Wi-Fi, then wait about a minute.
    • adb shell run-as com.duckduckgo.mobile.android.debug cat files/page-translation/packs/es-en/manifest-entry.json shows the manifest's version again.
  • Translate the Spanish page again.
    • It translates with no download sheet (screenshot).

@0nko 0nko added the auto Pull requests created through the Auto skill label Dec 3, 2026

@claude claude 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.

Claude Code Review

This repository is configured for manual code reviews. Comment @claude review for a one-time review, or @claude review always to subscribe this PR to a review on every future push.

Tip: disable this comment in your organization's Code Review settings.

@0nko
0nko requested a review from GerardPaligot December 3, 2026 16:40
@GerardPaligot GerardPaligot self-assigned this Dec 3, 2026

@GerardPaligot GerardPaligot 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.

@0nko Works as expected, I just have two comments covering rare edge cases. Depending on your thoughts, I'm happy to approve the PR as is or hold off, though I think they'd be worth fixing since the changes should be quick.

@0nko
0nko requested a review from GerardPaligot December 3, 2026 20:40
@0nko

0nko commented Dec 3, 2026

Copy link
Copy Markdown
Member Author

Thanks @GerardPaligot. I addressed both comments.

@GerardPaligot GerardPaligot 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.

Happy to approve this contribution without additional comments, nice work!

@0nko
0nko enabled auto-merge December 4, 2026 08:41
@0nko
0nko force-pushed the feature/ondrej/page-translate-update-pack branch from a1eed59 to 7598342 Compare December 4, 2026 16:29
@0nko
0nko disabled auto-merge December 4, 2026 16:29
@0nko
0nko enabled auto-merge December 4, 2026 16:29
@0nko
0nko added this pull request to the merge queue Dec 4, 2026
Merged via the queue into develop with commit 318c089 Dec 4, 2026
18 of 23 checks passed
@0nko
0nko deleted the feature/ondrej/page-translate-update-pack branch December 4, 2026 21:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

auto Pull requests created through the Auto skill

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants