vomebook commited on
Commit
ff072d5
·
1 Parent(s): 74afd5e

perf: reduce next-page display latency

Browse files
NEXT_PAGE_PERFORMANCE.md ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Next-Page Performance
2
+
3
+ ## Baseline (2026-10-09)
4
+
5
+ - Local baseline ref: `refs/baselines/next-page-20261009`.
6
+ - Commit: `aa82ae8101dd4a78a87c4897adbb3997fa7aa78e`.
7
+ - Baseline runtime source: `git show refs/baselines/next-page-20261009:static/app.js`.
8
+ - This is the local branch baseline, not the deployed Space revision `8e2dddb`.
9
+ - The ref preserves the committed source independently of future branch movement.
10
+ - Existing uncommitted Reader code, styles, tests and `READER_PROXY_REPORT.md`
11
+ were present; they are not part of this pagination baseline.
12
+
13
+ The baseline waits for the saved-page lookup before starting API prefetch,
14
+ checks only the bottom after prefetch completion, and starts scroll-triggered
15
+ pagination after rendering the current window. This site has no local search
16
+ Worker; local Worker prefetch applies only to the sibling GitHub project.
17
+
18
+ ## Acceptance
19
+
20
+ Keep exact ordered IDs, totals, generation validation, query cancellation, the
21
+ 5% append threshold, three-page/two-request API lookahead, and deferred
22
+ application during thumb dragging. A ready-page arrival must not repeatedly
23
+ append at an unchanged non-bottom scroll position.
24
+
25
+ All timing observations below describe controlled local fixtures, not production.
26
+ The baseline ref is local and is not automatically published by a normal push.
27
+
28
+ ## Implementation
29
+
30
+ - Nearest API page: allow 25 ms for an IndexedDB hit before starting transport;
31
+ farther speculative pages and position restoration retain their 150 ms lookup.
32
+ Memory hits and fast disk hits still avoid network requests. Timed-out reads
33
+ cannot replace the response subsequently used for that prefetch.
34
+ - Ready-page checks use the existing 5% threshold even away from the bottom.
35
+ Only the immediately next page may schedule this check. Repeated arrivals at
36
+ the same non-bottom logical offset cannot drain the prefetch buffer. Short
37
+ lists still automatically fill the viewport.
38
+ - Start scroll-triggered pagination before scheduling window rendering.
39
+ Multiple scroll events remain coalesced; thumb dragging retains deferred
40
+ application. API lookahead remains three pages with two requests in flight.
41
+
42
+ ## Repeatable Regression
43
+
44
+ Run from this project's root:
45
+
46
+ ```bash
47
+ node ../github-Search/tests/test_next_page_latency.js
48
+ node ../github-Search/tests/test_next_page_latency.js --compare-baseline
49
+ python3 -B -m unittest tests.test_prefetch_pipeline tests.test_paging_recovery tests.test_scroll_stability -v
50
+ python3 -B -m unittest tests.test_search_positions tests.test_recent_search_pages tests.test_static_contract.StaticFrontendContractTests.test_results_use_bounded_measured_virtual_window -v
51
+ ```
52
+
53
+ The sibling Node suite exercises both projects' actual functions with a fixed
54
+ clock. Comparison reads the old source directly from each retained Git ref;
55
+ it never checks out or replaces working files. For reviewing only pagination:
56
+
57
+ ```bash
58
+ git diff refs/baselines/next-page-20261009 -- static/app.js
59
+ ```
60
+
61
+ Do not restore the entire baseline tree over newer Reader work. The retained
62
+ baseline is intentionally fixed; do not repoint it for subsequent comparisons.
63
+
64
+ ## Observations (2026-10-09)
65
+
66
+ | Controlled fixture | Baseline | Current |
67
+ | --- | --- | --- |
68
+ | Stalled IndexedDB, next-page transport start | 150 ms | 25 ms |
69
+ | Scroll-triggered request starts before window paint | No | Yes |
70
+ | Ready next page at 5%, without another scroll event | Not appended | One page appended |
71
+
72
+ The 125 ms difference is eliminated cache-wait time in a stalled-disk fixture,
73
+ not an end-to-end or production latency claim. The real Chromium case confirms
74
+ that a page arriving after drag suppression is removed applies above the
75
+ threshold without a new scroll event, and leaves later cached pages buffered.
76
+
77
+ - Fixed-clock latency regression: 16 cases passed across both projects.
78
+ - Prefetch, paging recovery and scroll stability: 21 browser cases passed.
79
+ - Positions, recent-page storage and the changed virtual-window static contract:
80
+ 27 cases passed.
81
+ - The sibling page-generation and response-cache suites also passed for this site.
82
+ - Local preview: `http://127.0.0.1:8791/`.
83
+
84
+ ## Publication
85
+
86
+ Publication requested on 2026-10-10. The release is applied to the latest remote
87
+ branch in an isolated worktree, retaining remote Reader/index changes and local
88
+ uncommitted Reader work. The deployment commit is identifiable by
89
+ `perf: reduce next-page display latency`; Space runtime and read-only production
90
+ acceptance are verified separately after push.
static/app.js CHANGED
@@ -492,11 +492,11 @@ function saveRecentSearchPages(position, view, visibleEnd) {
492
  if (store) try { pruneSearchContentStore(store, RECENT_SEARCH_PAGE_MAX, RECENT_SEARCH_PAGE_TTL); } catch (_) {}
493
  }
494
 
495
- async function readRecentSearchPage(key, page, expected) {
496
  const id = [key, page];
497
  let entry = recentSearchPages.get(JSON.stringify(id));
498
  if (!entry && searchPositionDB?.objectStoreNames.contains("recent-pages")) entry = await new Promise(resolve => {
499
- const timer = setTimeout(() => resolve(null), 150);
500
  try {
501
  const request = searchPositionDB.transaction("recent-pages").objectStore("recent-pages").get(id);
502
  request.onsuccess = () => { clearTimeout(timer); resolve(request.result); };
@@ -3249,7 +3249,10 @@ function reconcileVirtualRows(items, start, end, topH, bottomH) {
3249
 
3250
  function scheduleVirtualRender() {
3251
  const afterScroll = arguments[0] === true;
3252
- if (afterScroll) VSCROLL.renderAfterScroll = true;
 
 
 
3253
  if (VSCROLL.renderFrame) return;
3254
  VSCROLL.renderFrame = requestAnimationFrame(() => {
3255
  VSCROLL.renderFrame = 0;
@@ -3260,7 +3263,6 @@ function scheduleVirtualRender() {
3260
  if (VSCROLL.isDraggingThumb) updateScrollThumb();
3261
  else updateScrollTrack();
3262
  }
3263
- if (!VSCROLL.isDraggingThumb) maybeLoadNextPage();
3264
  }
3265
  });
3266
  }
@@ -3706,7 +3708,7 @@ function prefetchSearchPages(base, template) {
3706
  if (data && expected && (data.generation !== expected.generation || data.total !== expected.total)) {
3707
  searchResponseCache.delete(cacheKey); data = null;
3708
  }
3709
- if (!data && expected) data = await readRecentSearchPage(key, page, expected);
3710
  if (!current()) return;
3711
  if (!data) data = await fetchSearchPage(cacheKey, base, body, controller.signal, APPEND_REQUEST_TIMEOUT);
3712
  if (!current()) return;
@@ -3714,7 +3716,7 @@ function prefetchSearchPages(base, template) {
3714
  rememberSearchPageMetadata(data);
3715
  setCachedSearchResponse(cacheKey, data);
3716
  if (page > STATE._loadedPage) STATE._pageCache[page] = data.results;
3717
- scheduleBottomLoad();
3718
  })().catch(() => {
3719
  // Foreground pagination owns retries and user-visible failure feedback.
3720
  }).finally(() => { controller.active.delete(page); pump(); });
@@ -3821,6 +3823,7 @@ async function doSearch(append = false, fromStart = false, restorePosition = fal
3821
  searchAbortController = new AbortController();
3822
  STATE._pageCache = {};
3823
  STATE._loadedPage = 0;
 
3824
  STATE._pendingPage = 0;
3825
  STATE._deferredAppendWhileDragging = false;
3826
  if (scrollLoadTimer) {
@@ -4565,12 +4568,17 @@ function resetPagingRecovery() {
4565
  updatePagingStatus();
4566
  }
4567
 
4568
- function scheduleBottomLoad(delay = 0) {
 
4569
  clearTimeout(pagingCheckTimer);
4570
  const generation = searchRequestId;
4571
  pagingCheckTimer = setTimeout(() => {
4572
  pagingCheckTimer = null;
4573
- if (generation === searchRequestId) maybeLoadNextPage(true);
 
 
 
 
4574
  }, Math.max(delay, pagingRetryAt - Date.now()));
4575
  }
4576
 
@@ -4599,6 +4607,7 @@ function maybeLoadNextPage(bottomOnly = false, retry = false) {
4599
  const loadedHeight = getVirtualTotalHeight();
4600
  const triggerPoint = loadedHeight * 0.05;
4601
  if (retry || isResultsAtBottom() || (!bottomOnly && scrollTop >= triggerPoint)) {
 
4602
  STATE.page = STATE._loadedPage + 1;
4603
  doSearch(true);
4604
  }
 
492
  if (store) try { pruneSearchContentStore(store, RECENT_SEARCH_PAGE_MAX, RECENT_SEARCH_PAGE_TTL); } catch (_) {}
493
  }
494
 
495
+ async function readRecentSearchPage(key, page, expected, timeoutMs = 150) {
496
  const id = [key, page];
497
  let entry = recentSearchPages.get(JSON.stringify(id));
498
  if (!entry && searchPositionDB?.objectStoreNames.contains("recent-pages")) entry = await new Promise(resolve => {
499
+ const timer = setTimeout(() => resolve(null), timeoutMs);
500
  try {
501
  const request = searchPositionDB.transaction("recent-pages").objectStore("recent-pages").get(id);
502
  request.onsuccess = () => { clearTimeout(timer); resolve(request.result); };
 
3249
 
3250
  function scheduleVirtualRender() {
3251
  const afterScroll = arguments[0] === true;
3252
+ if (afterScroll && !VSCROLL.renderAfterScroll) {
3253
+ VSCROLL.renderAfterScroll = true;
3254
+ if (!VSCROLL.isDraggingThumb) maybeLoadNextPage();
3255
+ }
3256
  if (VSCROLL.renderFrame) return;
3257
  VSCROLL.renderFrame = requestAnimationFrame(() => {
3258
  VSCROLL.renderFrame = 0;
 
3263
  if (VSCROLL.isDraggingThumb) updateScrollThumb();
3264
  else updateScrollTrack();
3265
  }
 
3266
  }
3267
  });
3268
  }
 
3708
  if (data && expected && (data.generation !== expected.generation || data.total !== expected.total)) {
3709
  searchResponseCache.delete(cacheKey); data = null;
3710
  }
3711
+ if (!data && expected) data = await readRecentSearchPage(key, page, expected, page === STATE._loadedPage + 1 ? 25 : 150);
3712
  if (!current()) return;
3713
  if (!data) data = await fetchSearchPage(cacheKey, base, body, controller.signal, APPEND_REQUEST_TIMEOUT);
3714
  if (!current()) return;
 
3716
  rememberSearchPageMetadata(data);
3717
  setCachedSearchResponse(cacheKey, data);
3718
  if (page > STATE._loadedPage) STATE._pageCache[page] = data.results;
3719
+ scheduleBottomLoad(0, page);
3720
  })().catch(() => {
3721
  // Foreground pagination owns retries and user-visible failure feedback.
3722
  }).finally(() => { controller.active.delete(page); pump(); });
 
3823
  searchAbortController = new AbortController();
3824
  STATE._pageCache = {};
3825
  STATE._loadedPage = 0;
3826
+ STATE._pagingAppendScrollTop = null;
3827
  STATE._pendingPage = 0;
3828
  STATE._deferredAppendWhileDragging = false;
3829
  if (scrollLoadTimer) {
 
4568
  updatePagingStatus();
4569
  }
4570
 
4571
+ function scheduleBottomLoad(delay = 0, readyPage = 0) {
4572
+ if (readyPage && readyPage !== STATE._loadedPage + 1) return;
4573
  clearTimeout(pagingCheckTimer);
4574
  const generation = searchRequestId;
4575
  pagingCheckTimer = setTimeout(() => {
4576
  pagingCheckTimer = null;
4577
+ if (generation !== searchRequestId) return;
4578
+ // A ready page may satisfy one scroll intent, not drain the lookahead buffer.
4579
+ if (readyPage && (readyPage !== STATE._loadedPage + 1 ||
4580
+ (STATE._pagingAppendScrollTop === getResultScrollTop() && !isResultsAtBottom()))) return;
4581
+ maybeLoadNextPage(!readyPage);
4582
  }, Math.max(delay, pagingRetryAt - Date.now()));
4583
  }
4584
 
 
4607
  const loadedHeight = getVirtualTotalHeight();
4608
  const triggerPoint = loadedHeight * 0.05;
4609
  if (retry || isResultsAtBottom() || (!bottomOnly && scrollTop >= triggerPoint)) {
4610
+ STATE._pagingAppendScrollTop = scrollTop;
4611
  STATE.page = STATE._loadedPage + 1;
4612
  doSearch(true);
4613
  }
tests/test_prefetch_pipeline.py CHANGED
@@ -66,6 +66,25 @@ class PrefetchPipelineTests(unittest.TestCase):
66
  self.page.wait_for_timeout(50)
67
  self.assertEqual(self.page.evaluate('[STATE.query,STATE.results.length,Object.keys(STATE._pageCache).length]'), ['paging-new',1,0])
68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  def test_sparse_window_prefetch_tracks_visible_position_and_reserves_a_slot(self):
70
  result = self.page.evaluate('''() => {
71
  const previous=resultWindow,loader=loadResultWindowPage,finder=findVirtualIndex;
 
66
  self.page.wait_for_timeout(50)
67
  self.assertEqual(self.page.evaluate('[STATE.query,STATE.results.length,Object.keys(STATE._pageCache).length]'), ['paging-new',1,0])
68
 
69
+ def test_ready_next_page_applies_at_threshold_without_another_scroll(self):
70
+ self.start_pipeline()
71
+ self.page.evaluate('aheadReleases[3]()')
72
+ self.page.wait_for_function('aheadCalls.includes(4)')
73
+ self.page.evaluate('aheadReleases[4]()')
74
+ self.page.wait_for_function('!!STATE._pageCache[4]')
75
+ self.page.evaluate('''() => {
76
+ VSCROLL.isDraggingThumb=true;
77
+ setResultScrollTop(getVirtualTotalHeight()*0.06);
78
+ }''')
79
+ self.page.wait_for_timeout(50)
80
+ self.assertEqual(self.page.evaluate('[STATE._loadedPage,STATE.isLoading]'), [1,False])
81
+ self.page.evaluate('VSCROLL.isDraggingThumb=false;aheadReleases[2]()')
82
+ self.page.wait_for_function('STATE._loadedPage===2 && !STATE.isLoading')
83
+ self.page.wait_for_timeout(100)
84
+ self.assertEqual(self.page.evaluate('STATE._loadedPage'), 2)
85
+ self.assertEqual(self.page.evaluate('STATE.results.map(r=>r.ID)'), [str(i) for i in range(200)])
86
+ self.assertEqual(self.page.evaluate('Object.keys(STATE._pageCache).map(Number).filter(p=>p<=4)'), [3,4])
87
+
88
  def test_sparse_window_prefetch_tracks_visible_position_and_reserves_a_slot(self):
89
  result = self.page.evaluate('''() => {
90
  const previous=resultWindow,loader=loadResultWindowPage,finder=findVirtualIndex;
tests/test_static_contract.py CHANGED
@@ -486,7 +486,9 @@ class StaticFrontendContractTests(unittest.TestCase):
486
  self.assertIn('renderAfterScroll: false', self.js)
487
  self.assertNotIn('let scrollTicking = false', self.js)
488
  self.assertIn('const scrollTrackUpdated = renderVisible();', self.js)
489
- self.assertRegex(self.js, r'if \(VSCROLL\.renderAfterScroll\)[\s\S]*?if \(!scrollTrackUpdated\) \{[\s\S]*?if \(VSCROLL\.isDraggingThumb\) updateScrollThumb\(\);[\s\S]*?else updateScrollTrack\(\);[\s\S]*?if \(!VSCROLL\.isDraggingThumb\) maybeLoadNextPage\(\);')
 
 
490
  self.assertRegex(self.js, r'updateScrollTrack\(\);\s*return true;')
491
  self.assertRegex(self.js, r'if \(updateView\) \{[\s\S]*?scheduleVirtualRender\(\);')
492
  self.assertIn('if (!dragFrame) dragFrame = requestAnimationFrame(applyPendingScrollTop)', self.js)
 
486
  self.assertIn('renderAfterScroll: false', self.js)
487
  self.assertNotIn('let scrollTicking = false', self.js)
488
  self.assertIn('const scrollTrackUpdated = renderVisible();', self.js)
489
+ scheduler = re.search(r'^function scheduleVirtualRender\([\s\S]*?^}', self.js, re.M).group()
490
+ self.assertRegex(scheduler, r'if \(afterScroll && !VSCROLL\.renderAfterScroll\) \{[\s\S]*?if \(!VSCROLL\.isDraggingThumb\) maybeLoadNextPage\(\);[\s\S]*?requestAnimationFrame')
491
+ self.assertRegex(scheduler, r'if \(VSCROLL\.renderAfterScroll\)[\s\S]*?if \(!scrollTrackUpdated\) \{[\s\S]*?if \(VSCROLL\.isDraggingThumb\) updateScrollThumb\(\);[\s\S]*?else updateScrollTrack\(\);')
492
  self.assertRegex(self.js, r'updateScrollTrack\(\);\s*return true;')
493
  self.assertRegex(self.js, r'if \(updateView\) \{[\s\S]*?scheduleVirtualRender\(\);')
494
  self.assertIn('if (!dragFrame) dragFrame = requestAnimationFrame(applyPendingScrollTop)', self.js)