Skip to content

fix: prevent stale header rules with versioned storage meta#88

Draft
Kirrrusha wants to merge 16 commits intomainfrom
fix/update-request-with-tab-windows
Draft

fix: prevent stale header rules with versioned storage meta#88
Kirrrusha wants to merge 16 commits intomainfrom
fix/update-request-with-tab-windows

Conversation

@Kirrrusha
Copy link
Copy Markdown
Collaborator

Summary

Исправляет Windows-специфичную гонку, когда при переключении вкладок и редактировании заголовков могли применяться устаревшие значения (старый снапшот из storage), перезаписывая актуальную конфигурацию.

Changes

  • Атомарное обновление DNR-правил: применяем declarativeNetRequest.updateDynamicRules({ removeRuleIds, addRules }) одним вызовом, чтобы избежать гонки remove→add.
  • Сериализация применения в background: добавлена очередь (single-flight), которая склеивает параллельные триггеры и гарантирует “latest wins”.
  • Строгая версия конфигурации: сохраняем headersConfigMetaV1 (seq, монотонный updatedAt) и в background пропускаем устаревшие снапшоты, даже если события приходят не по порядку.
  • Убрано лишнее применение на смене вкладки: DNR-правила глобальные, поэтому пересборка на tabs.onActivated только увеличивала вероятность гонок.
  • Убран legacy reload-путь: удалены updateOverrideHeaders/runtime reload message; обновления теперь идут через storage.onChanged.

Why this works

На Windows из-за другой латентности и планирования событий чаще происходили перекрывающиеся триггеры применения правил. Версионирование + очередь не позволяют применить старую конфигурацию “после” новой.

Test plan

  • pnpm test:unit
  • Ручная проверка (Windows):
    • Менять значения заголовков в popup и быстро переключать вкладки (несколько раз).
    • Проверить, что запросы уходят с последними значениями заголовков.
    • В логах background убедиться, что устаревшие снапшоты пропускаются (Apply skipped (stale meta)), а применения идут последовательно.

Notes

  • seq — best-effort при конкурентных записях; updatedAt принудительно монотонный и используется как tie-breaker.

github-actions Bot added a commit that referenced this pull request Jan 23, 2026
github-actions Bot added a commit that referenced this pull request Jan 23, 2026
@github-actions
Copy link
Copy Markdown

github-actions Bot commented Jan 23, 2026

github-actions Bot added a commit that referenced this pull request Jan 23, 2026
github-actions Bot added a commit that referenced this pull request Jan 30, 2026
github-actions Bot added a commit that referenced this pull request Jan 30, 2026
github-actions Bot added a commit that referenced this pull request Jan 30, 2026
github-actions Bot added a commit that referenced this pull request Feb 2, 2026
github-actions Bot added a commit that referenced this pull request Feb 2, 2026
github-actions Bot added a commit that referenced this pull request Feb 2, 2026
github-actions Bot added a commit that referenced this pull request Feb 4, 2026
github-actions Bot added a commit that referenced this pull request Feb 4, 2026
github-actions Bot added a commit that referenced this pull request Feb 4, 2026
github-actions Bot added a commit that referenced this pull request Feb 6, 2026
github-actions Bot added a commit that referenced this pull request Feb 6, 2026
github-actions Bot added a commit that referenced this pull request Feb 6, 2026
@Kirrrusha Kirrrusha force-pushed the fix/update-request-with-tab-windows branch from 13f91af to 1585555 Compare February 6, 2026 07:28
github-actions Bot added a commit that referenced this pull request Feb 6, 2026
github-actions Bot added a commit that referenced this pull request Feb 6, 2026
github-actions Bot added a commit that referenced this pull request Feb 6, 2026
@Kirrrusha Kirrrusha force-pushed the fix/update-request-with-tab-windows branch from 1585555 to c7d6752 Compare February 6, 2026 07:56
github-actions Bot added a commit that referenced this pull request Feb 6, 2026
github-actions Bot added a commit that referenced this pull request Feb 6, 2026
github-actions Bot added a commit that referenced this pull request Feb 6, 2026
@Kirrrusha Kirrrusha force-pushed the fix/update-request-with-tab-windows branch from c7d6752 to 92e9ea1 Compare February 6, 2026 08:14
github-actions Bot added a commit that referenced this pull request Feb 6, 2026
@Kirrrusha Kirrrusha force-pushed the fix/update-request-with-tab-windows branch from 86e0f30 to 386b0d7 Compare February 27, 2026 18:16
github-actions Bot added a commit that referenced this pull request Feb 27, 2026
github-actions Bot added a commit that referenced this pull request Feb 27, 2026
github-actions Bot added a commit that referenced this pull request Feb 27, 2026
github-actions Bot added a commit that referenced this pull request Mar 2, 2026
github-actions Bot added a commit that referenced this pull request Mar 2, 2026
github-actions Bot added a commit that referenced this pull request Mar 2, 2026
@Kirrrusha Kirrrusha force-pushed the fix/update-request-with-tab-windows branch from 5d6b119 to fae69b7 Compare March 2, 2026 19:33
github-actions Bot added a commit that referenced this pull request Mar 2, 2026
github-actions Bot added a commit that referenced this pull request Mar 2, 2026
github-actions Bot added a commit that referenced this pull request Mar 2, 2026
github-actions Bot added a commit that referenced this pull request Mar 3, 2026
github-actions Bot added a commit that referenced this pull request Mar 3, 2026
github-actions Bot added a commit that referenced this pull request Mar 3, 2026
Kirill Lebedenko and others added 16 commits April 16, 2026 17:07
- Add retry logic (3 attempts with exponential backoff) for transient
  DNR updateDynamicRules errors ("Internal error while updating dynamic rules")
- Re-throw errors from setBrowserHeaders to prevent queue state from updating
  when rules fail to apply
- Add detailed diagnostic logging for debugging header toggle issues
…start MV3 service workers are killed by Chrome after ~30 s of inactivity and restarted on demand Dynamic DNR rules persist across SW sessions but neither onStartup nor onInstalled fires on a plain SW restart so stale rules from a previous session eg for headers that were later disabled would stay active — meaning disabled headers kept being injected into requests until the user made a storage change Fix call applyHeadersFromStorageQueue'sw-init' at module load time so every SW restart reconciles DNR state with storage The existing meta/fingerprint deduplication prevents redundant applies when the state has not changed eg when onStartup also fires on browser start Add e2e tests in sw-restartspects that simulate the scenario by injecting a stale DNR rule directly triggering chromeruntimereload and asserting the rule is cleared by sw-init in the new worker session
…romeruntimereload is not usable in launchPersistentContext after calling it Playwright stops tracking the new service worker and the extension URL becomes permanently unreachable Instead the tests now simulate the same apply path applyHeadersFromStorageQueue which sw-init also calls by toggling isPausedV1 in storage This changes the storage fingerprint and forces a genuine apply without needing an actual SW restart Two separate storage writes are serialised via an explicit waitForRulesCount barrier between them to prevent the queue from collapsing both changes into a single apply that would see the original fingerprint Also fixes the storage key the correct key for the paused flag is 'isPausedV1' not 'isPaused'
…y After a plain SW restart (e.g. computer unlock), disabled headers from the previous session remain active as stale DNR dynamic rules until the full sw-init apply completes (~ ms). During that window, disabled headers are still injected into requests. Fix by adding clearDynamicRulesOnSwInit() that removes all dynamic rules immediately on SW boot before the apply reads storage. This reduces the window of incorrect behaviour from ~400 ms to ~5-10 ms (a single getDynamicRules round-trip). If the pre-clear fails, the apply handles cleanup as before — no regression. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
…When Chrome's dynamic rules API is broken Internal error the session fallback was removing ALL session rules including counteracting ones id >= 1_000_000_000 This left stuck dynamic rules with no counterpart causing disabled headers to be transmitted until the next apply Fix exclude counteracting rule IDs from the session fallback removal list They are cleaned up later in the same apply once stuck rules are reconciled Adds regression test covering the exact scenario from the debug logs
…nteracting session rules to override Chrome's dynamic > session ordering Chrome uses static > dynamic > session - Route onInstalled/onStartup through applyHeadersFromStorageQueue to fix race condition with clearDynamicRulesOnSwInit - Always clean up stale counteracting session rules even when stuckRuleIdslength === 0 - Add retry logic with exponential backoff to clearDynamicRulesOnSwInit - Update tests verify priority2 un-skip stale cleanup test add new cases
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