Skip to content

fix: paginate Explorer CRE load and batch-hydrate all_cres#931

Merged
northdpole merged 2 commits into
mainfrom
fix/explorer-paginated-cre-load
Jun 12, 2026
Merged

fix: paginate Explorer CRE load and batch-hydrate all_cres#931
northdpole merged 2 commits into
mainfrom
fix/explorer-paginated-cre-load

Conversation

@northdpole

Copy link
Copy Markdown
Collaborator

Summary

Fixes production H12 timeouts caused by GET /rest/v1/all_cres?page=1&per_page=1000 taking ~28–30s (N+1 link hydration + global frontend fetch on every page load).

  • Backend (Phase 1): Batch-hydrate CRE node/internal links in get_CREs / pagination paths (~4–5 queries per page vs N+1). Cap per_page at 100 on /rest/v1/all_cres.
  • Frontend scope (Phase 2): Move DataProvider from global App to Explorer-only ExplorerLayout. Tree view keeps same UX with scroll-to-load via IntersectionObserver. Force graph and circles call ensureFullExplorerData() for full dataset.
  • Incremental loading (Phase 3): Rewrite DataProvider for paginated fetch (20 CREs/page), IndexedDB cache v2, idle prefetch, and legacy full-store cache compatibility.

Closes #930. Related: #847, #848.

Performance (local, 522 CREs, standards_cache.sqlite)

Scenario Before (prod) After (local)
per_page=1000 ~28–30s → H12 Capped to 100 → ~47ms
per_page=20 page 1 ~15ms avg
Full drain (27 pages) ~301ms total
Home page triggers bulk /all_cres no /all_cres calls

Test plan

  • make test — 279 tests, 0 failures
  • black . — passed
  • npx prettier --check on frontend — passed
  • make frontend / webpack build — passed
  • Local hammer: 20× home page (no /all_cres), 50× concurrent paginated API (all 200)
  • Browser: /explorer tree renders; /explorer/force_graph populates dropdowns
  • CI green on this PR
  • Post-deploy: confirm no H12 on /all_cres in Heroku logs

Note: make mypy has ~1052 pre-existing repo errors on main; not introduced by this branch.

Made with Cursor

@coderabbitai

coderabbitai Bot commented Jun 12, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Summary by CodeRabbit

  • New Features

    • Infinite scrolling in Explorer with a dedicated layout wrapper and load-more sentinel
    • Manual "load full graph" path with visible progress and error reporting
  • Performance & Stability

    • Batch hydration of graph data for much faster list/tree assembly
    • Client-side pagination/caching overhaul for incremental loading
    • Server-side per-page cap enforced (100)
  • Tests

    • Added unit/integration tests covering pagination caps and hydrated link graphs
  • Other Updates

    • Simplified viewport meta and favicon handling; default page-size constant added

Walkthrough

Backend replaces per-CRE SQL hydration with batch hydration; API enforces a 100-item page cap. Frontend scopes DataProvider to Explorer, implements paginated incremental loading with IndexedDB cache, infinite scroll, and full-data preload for graph views. Tests and route wiring updated.

Changes

N+1 Elimination and Paginated Explorer

Layer / File(s) Summary
Backend batch hydration and link assembly
application/database/db.py
Introduces _hydrate_cres_batch() and helper methods _assemble_cre_internal_links() and _assemble_cre_node_links() to batch-load links, nodes, and internal links for multiple CREs at once, replacing per-CRE SQL queries. Updates get_CREs() to delegate to batch hydration.
Endpoint integration and pagination cap
application/database/db.py, application/web/web_main.py, application/tests/db_test.py, application/tests/web_main_test.py
Updates all_cres_with_pagination() and get_root_cres() to use batch hydration; adds MAX_ITEMS_PER_PAGE = 100 cap on /rest/v1/all_cres to bound request latency; includes unit and integration tests validating cap behavior and pagination correctness.
DataProvider pagination rewrite and caching
application/frontend/src/providers/DataProvider.tsx
Replaces react-query with imperative paginated loading persisted to a v2 IndexedDB cache, adding loadPage(), loadNextPage(), and ensureFullExplorerData(), plus bootstrap/hydration, tree reconstruction, idle prefetch, and new pagination/full-load state exposed via context.
App-level restructuring and ExplorerLayout scoping
application/frontend/src/App.tsx, application/frontend/src/pages/Explorer/ExplorerLayout.tsx
Removes global DataProvider from App.tsx; introduces ExplorerLayout component and withExplorerLayout() HOC to wrap Explorer routes with DataProvider, confining pagination and caching to Explorer views only.
Explorer infinite scroll and pagination
application/frontend/src/const.ts, application/frontend/src/pages/Explorer/explorer.tsx
Adds EXPLORER_CRE_PAGE_SIZE = 20 constant; implements IntersectionObserver sentinel to trigger loadNextPage() when user scrolls near bottom; tree grows as pages load and shows incremental loading/error states.
Graph views full-data preload
application/frontend/src/pages/Explorer/visuals/circles/circles.tsx, application/frontend/src/pages/Explorer/visuals/force-graph/forceGraph.tsx
Graph components call ensureFullExplorerData() on mount, display fullLoadProgress while loading the full dataset, and use dataLoadError for error reporting.
Route wrapping and bundled assets
application/frontend/src/routes.tsx, application/frontend/www/bundle.js.LICENSE.txt, application/frontend/www/index.html, application/frontend/src/index.html
Wrap Explorer routes with withExplorerLayout; update bundled license header and normalize HTML meta tags and favicons.
Tests: pagination cap and batch hydration verification
application/tests/web_main_test.py, application/tests/db_test.py
Add unit and integration tests ensuring per-page cap enforcement and that paginated all_cres results are hydrated with the full link graph.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Suggested reviewers

  • Pa04rth
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 22.22% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'fix: paginate Explorer CRE load and batch-hydrate all_cres' clearly and specifically summarizes the main changes: backend batch hydration and frontend Explorer pagination.
Description check ✅ Passed The description is directly related to the changeset, detailing the multi-phase approach (backend batch hydration, frontend pagination, incremental loading) and providing performance metrics, test results, and issue closure information.
Linked Issues check ✅ Passed The PR implements all three phases from issue #930: Phase 1 (batch-hydrate CREs, cap per_page), Phase 2 (scope DataProvider to Explorer, scroll-to-load), and Phase 3 (paginated incremental load with IndexedDB cache v2 and idle prefetch).
Out of Scope Changes check ✅ Passed All code changes align with the linked issue #930 objectives: backend batch hydration, per_page cap, DataProvider scoping, pagination controls, and test additions for the new pagination paths.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/explorer-paginated-cre-load

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint install failed due to a network error.


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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@northdpole
northdpole force-pushed the fix/explorer-paginated-cre-load branch from 5ce2efc to fe29d55 Compare June 12, 2026 11:06
@northdpole
northdpole requested a review from Pa04rth June 12, 2026 11:58
Fix production H12 timeouts from GET /all_cres?per_page=1000 by batching
N+1 link hydration in the DB layer, capping per_page at 100, scoping
DataProvider to Explorer routes with incremental page loads, and using
ensureFullExplorerData for graph views.

Closes #930. Related: #847, #848.

Co-authored-by: Cursor <cursoragent@cursor.com>
@northdpole
northdpole force-pushed the fix/explorer-paginated-cre-load branch from fe29d55 to ad73bc8 Compare June 12, 2026 12:02

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 7

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@application/frontend/src/pages/Explorer/visuals/circles/circles.tsx`:
- Around line 24-27: ensureFullExplorerData() is being called inside useEffect
without handling rejections so any pagination/full-load failure is ignored and
LoadingAndErrorIndicator gets error={null}; update the useEffect(s) that call
ensureFullExplorerData (the ones around the top useEffect and the block
referenced at lines 454-457) to await or chain the returned promise and catch
errors, storing the caught error in component state (e.g., setFullLoadError) and
pass that state into LoadingAndErrorIndicator's error prop; alternatively wrap
the call in try/catch inside an async IIFE or add .catch(err =>
setFullLoadError(err)) to ensure failures surface to the UI.

In `@application/frontend/src/providers/DataProvider.tsx`:
- Around line 165-169: The early-return in loadPage uses dataStoreRef.current
when loadingPageRef.current is set, which returns a stale snapshot instead of
the active fetch; change loadPage to return the in-flight promise for the
requested page (i.e., make loadingPageRef/current hold or reference the active
Promise and return that) so concurrent callers await the same fetch; apply the
same fix to the similar logic referenced around ensureFullExplorerData and the
block covering lines ~217-240 so all concurrent callers receive the active page
Promise rather than the stale dataStoreRef snapshot.
- Around line 165-203: The loadPage function currently swallows request errors
by using try/finally and falling back to an empty tree; change it to
try/catch/finally so you capture any axios error, set or propagate an explicit
error state (e.g., call a setter like setDataLoadError or rethrow) before the
finally block clears loading, and avoid updating dataStoreRef/current state with
an empty result on failure; specifically update the logic inside loadPage
(references: loadPage, loadingPageRef, setIsLoadingMore, dataStoreRef,
setDataStore, persistCache, rebuildDataTree) to only merge and persist on
successful fetch and to expose the error to the caller/UI, and apply the same
fix to the other similar loader function with identical behavior elsewhere in
this file.
- Around line 103-115: The buildTree recursion is mutating the same keyPath
array (pushed at line with keyPath.push(selfKey)), causing sibling calls to see
descendants as already visited; fix by not mutating the shared array—create a
new path for each recursion (e.g., clone keyPath or use keyPath.concat(selfKey))
and pass that new array into the recursive buildTree(x.document, store,
newKeyPath) calls so each branch has its own visited set; update references in
the function where keyPath is extended and where buildTree is invoked.

In `@application/frontend/src/routes.tsx`:
- Around line 115-127: ROUTES() currently calls withExplorerLayout(...) inline
for Explorer, ExplorerCircles, and ExplorerForceGraph which creates new
component identities on each call and causes remounts (resetting DataProvider
state); fix by creating and exporting/declaring persistent wrapped components
once (e.g., ExplorerWithLayout, ExplorerCirclesWithLayout,
ExplorerForceGraphWithLayout = withExplorerLayout(...)) outside of ROUTES(),
then update the route objects to reference those pre-wrapped components instead
of calling withExplorerLayout inside ROUTES().

In `@application/frontend/www/index.html`:
- Line 1: Update the viewport meta tag in index.html to allow pinch-zoom: remove
the user-scalable=no and maximum-scale=1 parameters from the meta element (the
<meta name="viewport" ...> in the head) so it reads something like
width=device-width, initial-scale=1 (you can keep minimum-scale=1 if desired) to
restore browser zoom for accessibility.

In `@application/tests/db_test.py`:
- Around line 2532-2534: The parity assertion is order-sensitive because
paginated_cre.todict() and collection.get_CREs(...)[0].todict() can have links
in different orders; update the test loop over paginated_cres to canonicalize
both CRE representations before asserting equality: fetch expected =
collection.get_CREs(external_id=paginated_cre.id)[0], convert both
expected.todict() and paginated_cre.todict() to comparable forms by normalizing
link lists (e.g., sort links or replace link lists with sets) and then assert
equality on the normalized dicts so order differences in links won't cause flaky
failures.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: abd50bfd-4872-4d56-85a5-1235209d2a6b

📥 Commits

Reviewing files that changed from the base of the PR and between 294b17e and ad73bc8.

📒 Files selected for processing (15)
  • application/database/db.py
  • application/frontend/src/App.tsx
  • application/frontend/src/const.ts
  • application/frontend/src/pages/Explorer/ExplorerLayout.tsx
  • application/frontend/src/pages/Explorer/explorer.tsx
  • application/frontend/src/pages/Explorer/visuals/circles/circles.tsx
  • application/frontend/src/pages/Explorer/visuals/force-graph/forceGraph.tsx
  • application/frontend/src/providers/DataProvider.tsx
  • application/frontend/src/routes.tsx
  • application/frontend/www/bundle.js
  • application/frontend/www/bundle.js.LICENSE.txt
  • application/frontend/www/index.html
  • application/tests/db_test.py
  • application/tests/web_main_test.py
  • application/web/web_main.py

Comment thread application/frontend/src/pages/Explorer/visuals/circles/circles.tsx
Comment thread application/frontend/src/providers/DataProvider.tsx
Comment thread application/frontend/src/providers/DataProvider.tsx Outdated
Comment thread application/frontend/src/providers/DataProvider.tsx
Comment thread application/frontend/src/routes.tsx
Comment thread application/frontend/www/index.html Outdated
Comment thread application/tests/db_test.py Outdated
Fix buildTree sibling keyPath mutation, serialize loadPage via promise
chain with exposed dataLoadError, hoist Explorer layout wrappers,
surface load failures in graph views, restore viewport zoom, and
harden pagination link parity test.

Co-authored-by: Cursor <cursoragent@cursor.com>

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@application/frontend/www/index.html`:
- Line 1: The HTML document is missing the root <html> element; add an opening
<html> tag immediately after the <!doctype html> declaration and a closing
</html> tag immediately after the existing </body> to properly wrap the <head>,
<body>, and the <div id="mount"> content and ensure valid HTML5 structure.
- Line 1: Update the protocol-relative CDN URL used for the Semantic UI
stylesheet so it explicitly uses HTTPS: locate the <link rel="stylesheet"
href="//cdn.jsdelivr.net/npm/semantic-ui@2.4.1/dist/semantic.min.css"/> entry in
the HTML and change the href to begin with "https://cdn.jsdelivr.net/npm/..." to
ensure a secure, explicit connection.
- Line 1: The document is missing a lang attribute on the root <html> element;
update the top-level HTML element so it includes a language declaration (for
example lang="en")—i.e., ensure the document starts with <!doctype html>
followed by an <html lang="en"> that wraps the existing <head> and <body> (and
corresponding closing </html>), or set the appropriate language value if
different.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: f95b762e-b152-4c31-8bce-ea89f1d7e2d4

📥 Commits

Reviewing files that changed from the base of the PR and between ad73bc8 and da8a077.

📒 Files selected for processing (9)
  • application/frontend/src/index.html
  • application/frontend/src/pages/Explorer/explorer.tsx
  • application/frontend/src/pages/Explorer/visuals/circles/circles.tsx
  • application/frontend/src/pages/Explorer/visuals/force-graph/forceGraph.tsx
  • application/frontend/src/providers/DataProvider.tsx
  • application/frontend/src/routes.tsx
  • application/frontend/www/bundle.js
  • application/frontend/www/index.html
  • application/tests/db_test.py
✅ Files skipped from review due to trivial changes (1)
  • application/frontend/src/index.html
🚧 Files skipped from review as they are similar to previous changes (5)
  • application/frontend/src/routes.tsx
  • application/frontend/src/pages/Explorer/visuals/force-graph/forceGraph.tsx
  • application/frontend/src/pages/Explorer/explorer.tsx
  • application/tests/db_test.py
  • application/frontend/src/providers/DataProvider.tsx

Comment thread application/frontend/www/index.html
@northdpole
northdpole merged commit e853cd3 into main Jun 12, 2026
10 checks passed
@northdpole
northdpole deleted the fix/explorer-paginated-cre-load branch June 12, 2026 15:31
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.

Fix production slowness: batch CRE queries, paginated Explorer load, scoped DataProvider

2 participants