Skip to content

Content Drive: use a materialized folder-first CTE for the candidate-scan query on large folders #37229

Description

@ihoffmann-dot

Description

Spike #37183 validated a concrete direction for the folder-listing candidate-scan query's planner instability on large folders (564ms on a ~21,000-child folder vs <20ms on folders up to ~4,000).

Validated on a live instance (raw SQL, not yet as an application-level change):

  • A usable index already exists (identifier_parent_path_asset_name_host_inode_key, unique on parent_path, asset_name, host_inode) — no schema change needed.
  • Wrapping the folder lookup in WITH folder_ids AS MATERIALIZED (...) before joining out to contentlet_version_info/contentlet/structure forces a stable, fast access path. Plain (non-materialized) CTEs get inlined by Postgres and can still hit the bad plan — materialization is what matters.
  • Measured: 21,383-child folder 470-490ms → 120-136ms. A folder that was already fast (39ms, 6,061 children) picks up a small, bounded cost (~63-68ms) — not the 3x regression an earlier, differently-shaped rewrite showed.
  • Root cause is not folder size — two folders of near-identical size (4,252 vs 6,061 children) showed opposite baseline behavior (227ms vs 39ms) depending on how their content is distributed relative to mod_date order, not their child count. A size-based special case would misroute both. Full detail: Spike: Content Drive folder-listing query has planner-driven latency on very large folders #37183.
  • At production scale in the reference dataset, 106 folders exceed 500 children — the population this affects.

Scope

  • Prototype the materialized-CTE approach as an actual BrowserAPIImpl change (not the simplified raw SQL tested in the spike) — the real query has additional dynamic predicates (structure exclusions, variant_id, language, etc.) not present in the spike's test query.
  • Preserve permission filtering exactly as today — untested in the spike.
  • Verify against every existing filter combination this query serves (tag, workflow, field filters), not just the unfiltered case.
  • Re-run the full size matrix from the original investigation (empty, small, medium, large, extreme folders) plus deep pagination, both roles (admin and permission-limited).

Explicitly out of scope

Acceptance Criteria

  • The materialized-CTE approach is implemented in BrowserAPIImpl and produces identical result sets to the current query, for empty/small/medium/large/extreme folders and at least one deep-pagination case
  • The largest tested folder drops from the current ~470-490ms baseline to within the same order of magnitude as the spike's ~120-136ms finding
  • No folder in the test matrix regresses by more than a small, bounded amount versus its current baseline (spike observed ~25-30ms on an already-fast folder; a large regression anywhere is a signal something differs from the spike's simplified query)
  • Permission filtering is verified unchanged for both an administrator and a permission-limited user
  • Behavior is verified unchanged when combined with tag, workflow, and field filters
  • Tests written and confirmed failing first (Constitution Principle V) before the implementation change
  • Coordination with Content Drive: field filter re-scans the folder candidate query up to 4x per request #37184 confirmed: the single-scan-per-request assumption that fix depends on still holds

Related

Activity

  1. moved this from New to In Review in dotCMS - Product Planningon Sep 5, 2026
  2. moved this from In Review to Spec In Review in dotCMS - Product Planningon Sep 5, 2026
  3. moved this from Spec In Review to QA in dotCMS - Product Planningon Sep 15, 2026
  4. removed their assignment
    on Sep 15, 2026
  5. fabrizzio-dotCMS commented on Sep 21, 2026

    @fabrizzio-dotCMS
    Member

    QA: verified, with one important caveat

    Ran the permission-scoped case that the original validation did not cover. The
    fix passes
    — details below — but the exercise surfaced a much larger
    optimization opportunity, which I am opening as a separate issue.

    Test conditions

    Local Docker instance built from main (ba7ab6f0a2), single binary with a
    local kill switch so both query shapes run against identical data and hardware.
    Both shapes confirmed in pg_stat_statements, not assumed.

    • PostgreSQL 18, shared_buffers 512MB, CACHE_PREPARED_STATEMENTS=false,
      chunking knobs pinned at their defaults (BROWSER_DB_CHUNK_FACTOR=10,
      BROWSER_DB_CHUNK_MIN_SIZE=200, BROWSER_DB_MAX_SCAN_ROWS=50000).
    • Synthetic content, not the 418k reference dataset from Spike: Content Drive folder-listing query has planner-driven latency on very large folders #37183: 59k
      identifiers total, folders at 0 / 500 / 4,252 / 6,061 / 7,154 (all file
      assets) / 21,383 children, plus a nested tree (11 items with 5,000- and
      4,000-child subfolders) and an 11,000-item folder where the test user can read
      only 151.
    • Three accounts: admin, a user who can read 1.4% of the large folder, and a
      user who can read none of it.
    • 7 repetitions per case, warmup discarded, VACUUM ANALYZE before each run.

    Results

    Correctness: 60 of 60 cases return the same set of items in both query
    shapes
    , across all three users, unfiltered and with text, tag and workflow
    filters, at first page and deep pagination. Some come back reordered, which is
    the new id.id tiebreaker doing its job on rows sharing a mod_date. Full page
    walks following the cursor to the end show no duplicated or skipped pages.

    As an administrator the fix is neutral to positive, which is what it was
    built for. Tag-filtered browsing improves substantially: on the 5,000-child
    folder the candidate scan drops from 731,010 to 233,720 buffers.

    With a permission-limited user, listing degrades sharply — expected, given
    how the algorithm works. Permission filtering happens in Java after the SQL, one
    chunk at a time, so a user who can see little forces the loop to fetch chunk
    after chunk. An admin needs 1; a user reading 1.4% needs 8; a user reading none
    of the 21,383-child folder needs 54. The per-chunk cost the fix added is paid
    every time:

    case chunks before the fix after
    21,383-child folder, admin 1 165 ms 185 ms
    11,000-child folder, reads 151 8 469 ms 573 ms
    11,000-child folder, reads none 28 1,347 ms 1,745 ms
    21,383-child folder, reads none 54 3,512 ms 5,128 ms

    Nothing hangs, nothing times out. The worst case in the matrix is a listing
    that takes about 5 seconds and then renders correctly. Note also that the two
    worst rows were already slow before this change — 3.5 seconds — so this is a
    pre-existing cost that the fix makes more expensive, not one it introduced.

    Caveat on scale: this database is 59k identifiers against the 418k where the
    fix was validated. There, contentlet is large enough that sorting it by
    mod_date is genuinely expensive and the CTE earned its 272→114 ms. The
    permission-limited case has never been measured at that scale, so the absolute
    numbers above should not be read as production figures. The mechanism —
    fixed per-chunk cost multiplied by the chunk count a restricted user forces —
    does not depend on dataset size.

    ⚠️ The important part: a large optimization is available

    The chunk size is a constant 400, and each chunk re-runs the whole candidate
    query with a larger OFFSET. PostgreSQL cannot jump to row N — it produces and
    discards the N preceding rows — so 54 chunks at growing offsets re-read the
    prefix 54 times. The cost is quadratic in chunk count, and this predates the CTE
    fix entirely.

    The loop already knows the visible/read ratio after its first chunk, so it can
    size the next fetch to what is actually needed instead of asking for 400 rows 54
    times. Prototyped and measured on the same rig:

    case today with adaptive sizing
    21,383-child folder, reads none 5,026 ms 1,258 ms -75%
    21,383-child folder, reads 151 5,009 ms 1,344 ms -73%
    11,000-child folder, reads none 1,619 ms 669 ms -59%
    11,000-child folder, reads 151 510 ms 242 ms -52%

    Blocks read per request fall 9x (5,876,712 → 652,968); chunks fall from 54 to 6.
    Admin is untouched. Full page walks return identical items in identical order.

    This puts the worst case at 1.3 s — below the 3.5 s it cost before this issue
    existed.
    It is ~40 lines in BrowserAPIImpl#getContentByChunks, behind a flag,
    and it needs unit and integration tests before it is a PR.

    I also prototyped keyset pagination to attack the quadratic directly and
    measured it as a dead end here: 6% slower than OFFSET, because the sort
    comes from an explicit sort over a four-table join rather than an index, so the
    predicate trims rows only after the work is already done. Recording it so nobody
    spends the time twice.

    Filed as #37665 (sub-issue of #36814), with the prototype, the measurements and
    the keyset dead end recorded there.

  6. removed their assignment
    on Sep 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions