Skip to content

perf(meditations,lectures): eliminate virtual-field N+1 on related-* + for-audience reads - #545

Merged
Ardnived merged 4 commits into
mainfrom
perf/related-endpoints-select-gating
Jul 5, 2026
Merged

Ardnived merged 4 commits into
mainfrom
perf/related-endpoints-select-gating

Conversation

@Ardnived

@Ardnived Ardnived commented Jul 5, 2026

Copy link
Copy Markdown
Contributor

Summary

  • Eliminates the virtual-field N+1 on the related-content endpoints: they fetched their candidate pool at depth ≥ 1 with no select, so every row ran the expensive per-row afterRead hooks — meditations tagAssignments (~4 user-choices queries/row) and the native lectures clips join — an N+1 that scaled with pool size (related-meditations was measured at 432 DB queries / 2.97 s for 25 rows in perf(meditations): eliminate virtual-field N+1 on ungated depth>=1 reads (related-* endpoints + REST clients) #541).
  • Adds a bounded include-mode select to each internal candidate-pool read, co-located with the shape helper it feeds, so those hooks are stripped before they run. Applies to related-meditations, related-lectures, and the sibling for-audience (same N+1, shared helper).
  • Response shapes are unchanged — this is purely how many rows/fields the internal reads hydrate.

Changes

  • src/lib/meditations/meditationShape.ts — export MEDITATION_CARD_SELECT (the fields shapeMeditation reads, incl. the co-selected duration→durationMinutes and subtleSystemNodeWeights→title dependencies).
  • src/lib/lectures/lectureShape.ts — export LECTURE_FEED_SELECT (fields shapeLecture + selectAudienceFeed read; fullLecture selected wholesale so a clip's parent still populates).
  • src/collections/Lectures/endpoints/relatedMeditations.ts, Meditations/endpoints/lectures.ts, Lectures/endpoints/forAudience.ts — apply the bounded selects to their payload.find candidate-pool reads.
  • src/collections/Lectures/Lectures.ts — defaultPopulate: { clips: false } bounds the clips join on a clip's nested fullLecture parent (select can't narrow a relationship's fields). Mirrors Meditations.defaultPopulate: { tagAssignments: false }.
  • .claude/rules/endpoints.md — new section documenting how to avoid this class of N+1 on future endpoints.

Test Results

  • Unit: 643 passed
  • Integration (affected specs): 89 passed across the three endpoint suites
    (lecture-related-meditations, meditation-lectures, lectures-for-audience)
  • Lint: ✓ No errors · Typecheck: ✓ No errors
  • Full suite + Playwright smoke run in CI / Railway preview

Regression guards (both verified to fail without the fix):

  • related-meditations: spy on payload.find, assert zero user-choices/frames sub-queries as the pool doubles (was 4/row — 12 finds for 3 rows before the fix).
  • for-audience: assert the clips join is absent from candidate lectures (select) and from a clip's nested fullLecture parent (defaultPopulate), with a direct-read baseline proving it otherwise populates.

Notes for reviewer

  • No migration — defaultPopulate is a read-time projection, not a schema change.
  • related-lectures shares the exact LECTURE_FEED_SELECT + defaultPopulate mechanism as for-audience; the clips-skip is regression-tested once (in the for-audience spec) rather than duplicated. Its own existing suite (89 passing across the 3 affected specs) covers shaping under the bounded select.
  • Deferred the issue's optional fix Ticket #2: Narrator Collection Implementation #2 (batching the user-choices lookups inside the tagAssignments factory) — unnecessary for the acceptance criteria since Ticket #1: Sentry Integration and Production Environment Setup #1 skips those hooks entirely, and organic client REST reads are already select-gated by validateClientQueryParamsHook. Worth a follow-up only if an ungated direct meditation read at depth ≥ 1 shows up in prod traces.

Closes #541

🤖 Generated with Claude Code

Ardnived and others added 4 commits July 5, 2026 20:53
The related-meditations / related-lectures / for-audience endpoints fetched
their candidate pool at depth >= 1 with no `select`, so every row ran the
expensive per-row afterReads — meditations `tagAssignments` (~4 user-choices
queries/row) and the native lectures `clips` join — an N+1 that scaled with
the pool size.

Add a bounded include-mode `select`, co-located with each shape helper
(MEDITATION_CARD_SELECT in meditationShape, LECTURE_FEED_SELECT in
lectureShape), so those hooks are stripped before they run. Co-select each
virtual field's dependency (`duration` for `durationMinutes`,
`subtleSystemNodeWeights` for `title`). For a clip's nested `fullLecture`
parent — which `select` can't narrow, since relationship fields are
boolean-only — add `Lectures.defaultPopulate: { clips: false }`, mirroring
`Meditations.defaultPopulate: { tagAssignments: false }`.

Closes #541

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Two regression guards for the bounded-select fix:

- related-meditations: spy on `payload.find` and assert zero user-choices /
  frames sub-queries fire as the daily pool doubles (before the fix this was
  4 user-choices finds per candidate — 12 for 3 rows).
- for-audience: assert the `clips` join is absent from candidate lectures
  (top-level select) and from a clip's nested `fullLecture` parent
  (defaultPopulate), while the parent's `metadata` still populates. A direct
  read is used as the baseline to show `clips` genuinely populates otherwise.

Refs #541

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
)

Add a rule section: any internal depth >= 1 read that shapes a pool of rows
must carry a bounded `select`, or every row's per-row afterReads (virtual +
native join fields) fire as an N+1. Covers co-locating the select with the
shape helper, co-selecting virtual-field dependencies, using the target
collection's `defaultPopulate` to bound expensive fields on populated
relationships (which `select` can't narrow), and count-based regression tests.

Refs #541

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Drops the local `findCollections` function for the inline
`findSpy.mock.calls.map((c) => c[0].collection)` idiom already used in
meditations.int.spec.ts, snapshotting per measurement (before/after).

Refs #541

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-545 July 5, 2026 20:08 Destroyed
@railway-app

railway-app Bot commented Jul 5, 2026

Copy link
Copy Markdown

🚅 Deployed to the SahajCloud-pr-545 environment in sahajcloud

Service Status Web Updated (UTC)
SahajCloud ✅ Success (View Logs) Web Jul 5, 2026 at 8:11 pm

@Ardnived
Ardnived merged commit e03e9af into main Jul 5, 2026
2 checks passed
@Ardnived
Ardnived deleted the perf/related-endpoints-select-gating branch July 5, 2026 20:26
Ardnived added a commit that referenced this pull request Jul 11, 2026
…pages) (#560) (#562)

* perf(app-cards): eliminate pages N+1 on for-audience reads (#560)

Bound the app-cards/for-audience endpoint's internal find to a select
excluding expensive virtual fields, mirroring the #545 pattern for
meditations/lectures endpoints. The unselected find at depth:1 ran every
field's afterRead across all candidate cards, including relationships to
pages, lectures, albums, and meditations — an N+1 scaled by the pool size.

Add APP_CARD_SELECT (all non-virtual fields) and pass it to the find call.
Destination relationships still populate at depth:1 but their expensive
fields (pages.appUrl, etc.) are gated by defaultPopulate on target collections.

Add regression test: spy on payload.find and assert pages are fetched in
a single batched query, not N times per card.

Fixes #560 (pages N+1 on for-audience).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* perf(meditations): optimize frames query in node weights computation (#560)

Add select parameter to the frames find call in recomputeWeightsForMeditation
to only fetch the subtleSystemNode relationship, avoiding unnecessary data
fetching. This makes the frames query more efficient even though it's called
once per meditation (not per-row N+1).

Also add regression test on the meditation-lectures endpoint to verify frames
queries stay bounded as pool size grows (≤2 queries for 1 meditation).

Refs #560.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>

This branch was successfully deployed

No deployments
sahajcloud / SahajCloud-pr-545 — ecbfe919 Deployed Jul 5, 2026 by railway-app[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant