Skip to content

perf(pages): lazy-load documentation content by language - #1992

Merged
lizhengfeng101 merged 4 commits into
alibaba:mainfrom
wzxsdf:issue-1895-lazy-load-docs
Nov 18, 2026
Merged

lizhengfeng101 merged 4 commits into
alibaba:mainfrom
wzxsdf:issue-1895-lazy-load-docs

Conversation

@wzxsdf

@wzxsdf wzxsdf commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

Description

Split documentation content by language so opening a docs page downloads only the selected language's bundle instead of all five.

Fixes #1895

Implementation

  • Lightweight directory — pages/src/content/docs/index.ts no longer imports any Markdown body. It holds the canonical slug order, per-language availability, and a cached on-demand loader, so importing it stays lightweight.
  • Five language content bundles — en/zh/ja/ko/ru.ts each import their language's Markdown behind an explicit import() boundary, so webpack emits five independent chunks. loadLanguageContent shares in-flight requests, caches successful loads for the session, and evicts failed loads so they stay retryable.
  • Shared page/search data — DocsPage and the full-text search read the same LoadedDocContent. The search hook contract is unchanged, so blog search is unaffected. English fallback loads only when the active page or an active search in a partial locale needs it — never speculatively; a transient download failure is never treated as a missing translation.

Behavior details:

  • Loading/error/retry states are confined to the content area; navigation and the page shell stay visible while content loads.
  • Stale responses after a language switch are ignored for page content, titles, headings, and search results.
  • vitest.config.ts gains a raw-source transform for .md that mirrors webpack's asset/source rule, so tests import the real content files.

Verification

  • npm run lint and npm run typecheck are clean (two pre-existing warnings in MarkdownRenderer.tsx untouched).
  • npm test: 81/81 — 65 existing tests plus 16 new ones covering loader caching/in-flight sharing/retry, directory-vs-bundle consistency, search order and English fallback, and page loading/race/retry behavior.
  • npm run build: five per-language async chunks (en 249 KiB, ja 337 KiB, ko 312 KiB, zh, ru 421 KiB); no Markdown body remains in the entry or route chunks.
  • npm run size: 97.12 kB against the 150 kB limit.

AI/LLM Disclosure

This pull request was prepared with AI assistance: code inspection, implementation, and test preparation were done with the ZCode agent (GLM model). I reviewed and understand every change in this PR.

Split the docs content index into a lightweight directory (slug order,
language availability, cached loader) plus five per-language content
bundles behind explicit import() boundaries. The docs page and
full-text search read the same loaded language content, English
fallback loads only when a partial locale needs it, failed loads stay
retryable, and stale responses are ignored after a language switch.
@CLAassistant

CLAassistant commented Nov 18, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@github-actions

github-actions Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

🔍 OpenCodeReview found 4 issue(s) in this PR.

  • ✅ Successfully posted inline: 3 comment(s)
  • ❌ Failed to post inline: 1 comment(s)

maintainability · medium

📄 pages/src/pages/DocsPage.tsx (L535-L541)

⚠️ GitHub could not post this as an inline comment: Lines 535-541 could not be resolved (outside PR diff hunks)

The Prev/Next pagination section renders unconditionally, including during loading and error states. This means users will see navigation buttons below the loading spinner or error message, which is visually inconsistent and potentially confusing. Consider wrapping the pagination block inside the {docState.status === 'ready' && ...} conditional, or adding a separate guard like {docState.status === 'ready' && (<div>...</div>)} around the pagination.

zh: DOC_SLUG_ORDER,
ja: DOC_SLUG_ORDER,
ko: DOC_SLUG_ORDER,
ru: DOC_SLUG_ORDER,

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.

bug · low
Misleading partial-locale setup for Russian: The comment in ru.ts states "Russian is an incremental locale: entries missing here fall back to English," and the availableTranslations / isPartialLocale infrastructure exists to support partial locales. However, ru is currently mapped to the full DOC_SLUG_ORDER, so isPartialLocale('ru') returns false and hasTranslation() returns true for every slug.

This is technically correct today (all 19 Russian .md files exist), but the comment/code mismatch is confusing. If a future maintainer removes a Russian translation expecting the fallback mechanism to kick in, they also need to remember to remove the slug from availableTranslations.ru — otherwise hasTranslation will lie and the page won't load the English fallback.

Either update the ru.ts comment to reflect that Russian is currently complete, or add a test/assertion that validates availableTranslations stays consistent with what each bundle actually exports.

| 'faq'
| 'chatgpt-preview';

export type LocalizedDocs = Partial<Record<DocSlug, string>>;

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.

maintainability · medium
Type safety gap: LocalizedDocs is defined as Partial<Record<DocSlug, string>>, which makes every slug optional. This means TypeScript will not flag a missing key in any language bundle — including English, which should always be complete. If a contributor accidentally removes or misspells a key in en.ts, the build succeeds and rawFor() silently returns '' at runtime.

Consider introducing a stricter type for bundles that must be complete:

export type CompleteLocalizedDocs = Record<DocSlug, string>;

Then use CompleteLocalizedDocs for en.ts (and other complete locales) while keeping LocalizedDocs (Partial) only for truly incremental locales and the LoadedDocContent.docs field. This gives you compile-time enforcement where it matters most.

Comment thread pages/src/pages/DocsPage.tsx Outdated
/* Best-effort fallback: the load stays retryable via the next trigger. */
});
return () => { cancelled = true; };
}, [docState, activeSlug, searchQuery]);

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.

performance · medium
Using the entire docState object as a dependency causes this effect to re-run on every state transition (e.g., loading→ready, ready→error, and even after the fallback's own setDocState call adds English). While the early-return guards prevent redundant fetches, each re-run still triggers cleanup and re-subscription.

Consider deriving more stable dependencies instead, e.g.:

const loadedLanguage = docState.status === 'ready' ? docState.content.language : null;
const hasEnglish = docState.status === 'ready' ? !!docState.content.english : false;

Then depend on [loadedLanguage, hasEnglish, activeSlug, searchQuery]. This avoids re-triggering the effect when unrelated state transitions occur (e.g., going from loading to ready for the same language, or the fallback's own update adding english).

- type complete locales as Record<DocSlug, string> so a missing key
  fails at compile time; keep Partial only for incremental bundles
- derive scalar dependencies for the English-fallback effect so
  unrelated docState transitions do not re-trigger it
- render prev/next pagination only once content is ready
- clarify the Russian bundle's maintenance contract with the
  availability directory
@lizhengfeng101

Copy link
Copy Markdown
Contributor

@wzxsdf Thanks for the language-level split. Pages CI is green (81 tests), and the build output confirms separate language chunks. Before merging, please address the following two medium-severity issues and complete the verification requested by #1895.

1. Search reports "no results" while its content is still loading or has failed

runDocsSearch returns [] when content is unavailable, but the search modal renders docs.search.noResults for any non-empty query with zero results.

Opening search and typing during a cold language load therefore looks like a completed search with no matches; a failed download produces the same misleading state. Results do update on eventual success, but pending and failed searches need their own loading/error presentation and an actionable retry. Only show "no results" once all content required for that search is ready.

2. English fallback failures leave missing pages blank without a retry action

The fallback catch ignores the rejection while docState remains ready. With a partial locale, if the requested article is missing and the English chunk fails, the page has an empty body and no error/retry UI. Search can also remain incomplete. Keeping the current page and query unchanged does not trigger another request; evicting the failed loader promise alone is not sufficient recovery.

All five shipped locales are currently complete, so this is not a claim that their existing translated pages fail. However, preserving partial-locale fallback is an explicit requirement of #1895. Please track fallback loading/error state and expose a retry for the required English request, including when search needs it.

Verification to complete before merge

  • Search regression tests: open search before content resolves; cover failure and successful retry, query reevaluation after arrival, and language switching with a query open. Assert loading/error states rather than premature "no results".
  • Fallback regression tests: use a partial-locale fixture even though shipped locales are complete. Exercise page and search fallback, English loading/failure/retry, and ensure fully translated pages do not request English unnecessarily. The current page tests mock hasTranslation as always true, isPartialLocale as always false, and searchDocs as always empty, so they cannot catch these paths.
  • Asynchronous navigation verification: with delayed content, verify direct links with fragments, heading/TOC updates, article navigation, browser back/forward, and rapid language switches. Confirm scrolling happens after the requested content is rendered and stale responses do not replace current content or search results.
  • Before/after browser Network evidence required by perf(pages): lazy-load documentation content by language #1895: use production builds, the same document/language, and a cold cache. Show actual transferred documentation bytes and that unused language chunks are not fetched, including after the page settles. Distinguish compressed transfer sizes from uncompressed asset sizes. The reported 97.12 kB size-limit result covers dist/*.bundle.js, not the language *.chunk.js, so it does not establish this comparison.

Reviewed snapshot: 667ce16243e4ede83de8de65a62141c2142f8630. The recommendation is to resolve these issues and supply the targeted verification before merging; per-article splitting or eliminating every webpack size warning is not being requested.

AI-assisted review using OpenAI Codex and ocr.

- the search modal reports loading and error states with a retry
  action while its content is pending or failed, and shows no results
  only once every required content has arrived
- the English fallback loads through a tracked state machine, so a
  missing article or an active search in a partial locale surfaces
  loading, failure and retry states instead of a blank body or a
  silent catch
- add regression tests for search content states, partial-locale
  fallback, and asynchronous navigation (fragment scroll, TOC,
  history back/forward, rapid language switches)
@wzxsdf

wzxsdf commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

@lizhengfeng101 Thanks for the detailed review — both issues are addressed in bc9aed6, along with the four verification items.

1. Search reports loading/error states instead of premature "no results"

searchContentStatus (loading / error / ready) derives from the main language state plus the English fallback state. The search modal shows a loading indication while its content is pending, an error message with a retry action when the underlying load failed (the retry re-requests whichever load failed), and docs.search.noResults only once every content the search depends on has actually arrived.

2. Fallback failures are tracked and retryable

The English fallback now runs through a tracked state machine (idle / loading / ready / error) separate from the main language state. A missing article in a partial locale shows the content-area loading state and then the article; a failed English request shows the error state with a Retry button that re-requests English — from the page and from the search modal. A failed attempt never auto-retries in a loop; recovery happens through the retry action or a changed trigger (page, query, or language).

Verification

Tests — 92 passing (was 81):

  • Search regression: opening search before content resolves shows "Searching...", not "no results"; a failed load shows an error with a working retry; queries re-evaluate when content arrives; switching languages with a query open transitions back to loading and ignores stale results.
  • Fallback regression: the page tests no longer stub hasTranslation/isPartialLocale unconditionally — a partial-locale fixture drives page fallback, search fallback, English loading/failure/retry, and asserts that fully translated pages never request English.
  • Async navigation: fragment scroll fires only after the requested content renders; the TOC populates on arrival; history back/forward re-renders content without reloading the language; rapid language switches keep only the newest response for content, headings and search.

Browser network evidence — production builds of main (d30f938) and this PR, same document (/docs/quickstart), cold cache (fresh profile, Network.setCacheDisabled), real Chrome, wire-transfer bytes from CDP:

Scenario Docs content transferred (wire) Language bundles fetched Requests after 5 s settle
main 445.7 KB in docs-page.*.chunk.js (uncompressed 1,603 KB) one chunk with en+zh+ja+ko+ru 0
PR, English 91.1 KB (en bundle, uncompressed 267 KB) en only 0
PR, Chinese 94.8 KB (zh bundle, uncompressed 249 KB) zh only 0

The PR build ships five independent language bundles (en 267 KB, zh 249 KB, ja 337 KB, ko 312 KB, ru 421 KB uncompressed); opening a page fetches only the selected language's bundle, and the other four are never requested — including after the page settles. Compressed transfer sizes are reported separately from the uncompressed asset sizes above.

@lizhengfeng101

Copy link
Copy Markdown
Contributor

@wzxsdf Thanks for the follow-up. The previous two findings are addressed in bc9aed6: search now distinguishes loading/error from completed empty results, and English fallback failures expose a retry. The added tests and before/after Network figures also address the earlier verification requests in substance.

Two medium-severity issues remain before merge:

1. P2: The new tests fail the required English-source check

DocsPage.test.tsx contains unapproved non-English literals at lines 335, 343, 358, 379, 382, 405, and 413. This file is outside the translation-table exemption and those lines have no explicit fixture exemption.

The repository's unchanged English-source verifier was run read-only against this snapshot and exited 1, reporting exactly these seven lines. Since english-check is a prerequisite of make check, the required check cannot currently pass, independently of the reported 92 passing site tests.

Please reference the existing translation-table values in these assertions, or add narrowly scoped allow-non-english: <reason> markers for intentional localized fixtures. Do not exempt the whole test directory.

2. P2: Retry cannot recover an obsolete language chunk after deployment

The main-language catch and English-fallback catch discard the error, while the retry handlers only rerun the same dynamic import.

A concrete affected workflow is:

  1. A reader opens English documentation and leaves the tab open.
  2. A deployment replaces the site, and an old language chunk is no longer available.
  3. The reader first switches to that language. The old runtime requests the old content-hashed URL and fails.
  4. Clicking Retry requests that same obsolete URL again; clearing the application promise cache does not update the runtime's chunk mapping.

The existing route ErrorBoundary already provides guarded reload recovery for chunk-load errors, but the locally caught asynchronous failures bypass it. Previously, opening documentation loaded all languages, so this first-switch-after-deployment failure was not introduced by a separate language request.

Please retain in-place retry for transient failures, as #1895 requires, while providing a guarded reload escape path for persistent/stale chunk failures, covering both the selected language and English fallback. An explicit, verified historical-asset retention policy is another possible solution; the current deployment workflow does not establish one. Add a regression case for an old runtime requesting an unavailable language chunk.

This second finding is based on the loading/error paths and deployment configuration; a real cross-deployment browser reproduction was not performed during this review.

Verification before merge

  • Resolve the English-source check failure and provide the required checks for the updated head, including make check and the site checks from perf(pages): lazy-load documentation content by language #1895. At review time, only the CLA status was visible for bc9aed6, not a current-head Pages CI result.
  • Verify stale-chunk recovery without regressing successful in-place retries for transient failures.

The language-level split remains appropriate. First-use language switching needing a network connection is an intentional consequence of lazy loading, not a request to prefetch all languages or expand this PR into per-article splitting. The reported Network measurements were not independently rerun in this review.

Reviewed snapshot: bc9aed6f2014777410baf30426b78372d759cba4, targeting main. Please address the two items and establish current-head verification before merging.

AI/LLM disclosure: this follow-up review used OpenAI Codex and ocr. Model identifiers were not captured in the review record. Publication was explicitly approved by the maintainer.

Keep transient language and fallback failures retryable in place, then
expose the guarded page reload recovery path when the same chunk failure
persists across a retry. Share chunk classification and reload handling
with ErrorBoundary, and cover stale chunk recovery for main and fallback
content.

Use translation-table values in localized test assertions so the required
English-source check remains clean.
@wzxsdf

wzxsdf commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

@lizhengfeng101 The two remaining P2 items are addressed in 0d9501e.

English-source check

DocsPage.test.tsx now references the existing en/zh translation tables for localized assertions instead of embedding non-English literals. The repository verifier reports:

  • No unapproved non-English text in 875 scanned source files.

Persistent stale-chunk recovery

  • Transient main-language and English-fallback failures still recover in place through the existing Retry action.
  • Errors are retained and classified with the shared isChunkLoadError helper.
  • After the same chunk target fails again, the page and search error states expose the existing localized Reload action.
  • reloadAfterChunkError clears the one-shot session guard before reloading, allowing the new runtime to obtain current content-hashed chunk mappings while preserving the ErrorBoundary loop guard.
  • Retry attempts are keyed by the active language/fallback request, so a previous language's failure cannot cause a new language's first failure to look persistent.

New regression coverage

  • ErrorBoundary chunk classification and guarded explicit reload.
  • Transient main-language failure with successful in-place retry.
  • Repeated stale main-language chunk failure with Reload recovery.
  • Repeated stale English-fallback chunk failure with Reload recovery.

Current-head verification

  • Pages tests: 97/97 passed.
  • npm run lint: 0 errors (the same two pre-existing hook warnings remain).
  • npm run typecheck: passed.
  • Production webpack build: passed.
  • npm run size: 98.89 kB brotlied, below the 150 kB limit.
  • Production smoke checks: /, /docs/quickstart, /docs/contributing, /features, and /404.html (after its static-server redirect) all returned 200 with bundle references.
  • Repository make check: passed, including license, English-source verification, tidy, gofmt, and vet.

The cold-cache browser measurements remain consistent with the earlier evidence: with a real Chrome profile and production builds, English fetched only the English docs chunk (91.1 KB wire) and Chinese fetched only the Chinese docs chunk (94.8 KB wire); the other language chunks were not requested, and there were zero requests after the 5-second settle window.

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

LGTM

@lizhengfeng101
lizhengfeng101 merged commit 8f9ce54 into alibaba:main Nov 18, 2026
15 checks passed
@lizhengfeng101

Copy link
Copy Markdown
Contributor

Thanks for the work on this PR, @wzxsdf. It has been merged, and we are tracking the two remaining partial-locale cases separately in #1994: stale English-fallback error state after switching languages, and internal fragment navigation when fallback content loads asynchronously.

Please verify both scenarios against current main using the fixtures described in #1994, then fix any confirmed failures and add the regression tests. If either scenario does not reproduce, please document your setup and results there.

I tried assigning #1994 to you, but GitHub did not accept the assignment. Could you leave a comment on #1994 to acknowledge the follow-up? We can then retry the assignment.

AI assistance: this message was drafted with OpenAI Codex; the model identifier is not available in the conversation record. Posting was explicitly requested by the maintainer.

@wzxsdf

wzxsdf commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

@lizhengfeng101 text
Thanks for the follow-up. I’m happy to take this on.
I’ll first reproduce both partial-locale scenarios against the current main branch using the fixtures described in #1994. I’ll then fix any confirmed failures and add regression tests. If either scenario does not reproduce, I’ll document the setup and results in this issue.
I acknowledge the follow-up and am happy to be assigned to #1994.

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.

perf(pages): lazy-load documentation content by language

3 participants