Skip to content

perf(core): fold byline + taxonomy hydration into the content query - #1619

Merged
ascorbic merged 8 commits into
mainfrom
perf/fold-hydration-into-content
Jun 25, 2026
Merged

ascorbic merged 8 commits into
mainfrom
perf/fold-hydration-into-content

Conversation

@ascorbic

@ascorbic ascorbic commented Jun 25, 2026 •

Copy link
Copy Markdown
Member

What does this PR do?

Folds byline and taxonomy-term hydration into the content query. loadEntry/loadCollection previously issued three round trips per fetch — the content row, then a _emdash_content_bylines join, then a content_taxonomies join. This adds the hydration as correlated JSON-array subqueries on the content query (generalizing the existing _emdash_seo join), so a fetch is one round trip.

Each subquery correlates on <entry>.id, so the base query stays one row per entry — no join fan-out and no duplicated content payload (a naive LEFT JOIN of two many-to-many relations would Cartesian-explode and repeat the portable-text body on every row).

Measured per-page statement counts (sqlite query-counts harness), main vs this PR:

route before after
/ (index) 11 6
/posts/[slug] 24 17
/pages/about 10 5
/category/[slug] 15 10
/rss.xml 5 1
/contributors-naive 18 5

Each getEmDashEntry/getEmDashCollection drops its byline round trip, its taxonomy round trip, and the taxonomy-defs applicability read.

Type of change

  • Bug fix
  • Feature (requires maintainer-approved Discussion)
  • Refactor (no behavior change)
  • Translation
  • Documentation
  • Performance improvement
  • Tests
  • Chore (dependencies, CI, tooling)

Implementation notes

  • Dialect-aware aggregation in foldedHydrationSelects (loader.ts): SQLite json_group_array/json_object (returns a JSON string) vs Postgres json_agg/json_build_object coalesced to [] (returns parsed JSON). stashFolded handles both. Ordering is done in the consumer (terms by label, credits by sortOrder), not in the aggregate, since the dialects differ there.
  • Locale correctness (getEmDashEntry/getEmDashCollection hydrate taxonomy terms using request/default locale instead of explicit query locale #1441): the terms subquery correlates on the entry's own locale (t.locale = <entry>.locale), so an fr entry gets its fr term variants — covered by a test on both dialects.
  • Byline fallbacks: the fold expresses the common case (explicit credits). The consumer falls back to the existing query path when an entry has a byline reference (authorId/primaryBylineId) but no folded credit (author-fallback, or a locale-mismatched credit), or when byline custom fields are registered (which the fold can't carry).
  • New tests/integration/loader-fold.test.ts runs under describeEachDialect (entry + list, bylines + terms, locale variant, empty case) — validated on SQLite and a local Postgres.

Checklist

  • I have read CONTRIBUTING.md
  • pnpm typecheck passes
  • pnpm lint passes
  • pnpm test passes — 4109 sqlite + full Postgres parity (4231 with EMDASH_TEST_PG), 185 cloudflare
  • pnpm format has been run
  • I have added/updated tests for my changes
  • User-visible strings wrapped for translation — n/a (no admin UI strings)
  • I have added a changeset (emdash, patch)
  • New features link to an approved Discussion — n/a (performance improvement)

AI-generated code disclosure

  • This PR includes AI-generated code — model/tool: Claude Opus 4.8 (opencode). Validated on both SQLite and a local Postgres; a self-review caught and fixed an i18n term-locale gap and a null-locale byline fallback gap before submission. An adversarial cross-model review pass is recommended.

Notes

  • The sqlite query-counts snapshot is updated here; the d1 snapshot will be regenerated by CI (the fold applies equally to D1, which is SQLite-backed).
  • Follow-up opportunities not in this PR: fold the author-fallback into SQL (currently a query-path fallback), and chrome cross-request caching.

Try this PR

Open a fresh playground →

A full working EmDash site, deployed from this branch. Each visit gets its own session-scoped sandbox: no login needed and no shared state. Try the admin, edit content, hit the public site.

Tracks perf/fold-hydration-into-content. Updated automatically when the playground redeploys.

loadEntry/loadCollection now hydrate bylines and taxonomy terms via correlated JSON-array subqueries in the content query instead of two follow-up round trips. Per-page query counts drop substantially (demo article 24->17, index 11->6).

- Dialect-aware aggregation (SQLite json_group_array/json_object string; Postgres json_agg/json_build_object parsed JSON), validated on both.
- Terms correlate on the entry's own locale (#1441); credits sorted in the consumer (dialect-neutral).
- Entries with byline custom fields or a missing/locale-mismatched explicit credit fall back to the existing query path.
@changeset-bot

changeset-bot Bot commented Jun 25, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 2302e2d

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 16 packages
Name Type
emdash Patch
@emdash-cms/cloudflare Patch
@emdash-cms/sandbox-workerd Patch
@emdash-cms/fixture-perf-site Patch
@emdash-cms/perf-demo-site Patch
@emdash-cms/cache-demo-site Patch
@emdash-cms/do-demo-site Patch
@emdash-cms/do-solo-demo-site Patch
@emdash-cms/admin Patch
@emdash-cms/auth Patch
@emdash-cms/blocks Patch
@emdash-cms/gutenberg-to-portable-text Patch
@emdash-cms/x402 Patch
create-emdash Patch
@emdash-cms/auth-atproto Patch
@emdash-cms/plugin-embeds Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Jun 25, 2026 •

Copy link
Copy Markdown

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Updated (UTC)
✅ Deployment successful!
View logs
emdash-demo-cache 2302e2d Jun 25 2026, 10:52 AM

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Jun 25, 2026 •

Copy link
Copy Markdown

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Updated (UTC)
✅ Deployment successful!
View logs
docs 2302e2d Jun 25 2026, 10:52 AM

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Jun 25, 2026 •

Copy link
Copy Markdown

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Updated (UTC)
✅ Deployment successful!
View logs
emdash-playground 2302e2d Jun 25 2026, 10:52 AM

@github-actions

Copy link
Copy Markdown
Contributor

Scope check

This PR changes 592 lines across 6 files. Large PRs are harder to review and more likely to be closed without review.

If this scope is intentional, no action needed. A maintainer will review it. If not, please consider splitting this into smaller PRs.

See CONTRIBUTING.md for contribution guidelines.

@github-actions github-actions Bot added the review/needs-review No maintainer or bot review yet label Jun 25, 2026
@pkg-pr-new

pkg-pr-new Bot commented Jun 25, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@emdash-cms/admin

npm i https://pkg.pr.new/@emdash-cms/admin@1619

@emdash-cms/auth

npm i https://pkg.pr.new/@emdash-cms/auth@1619

@emdash-cms/auth-atproto

npm i https://pkg.pr.new/@emdash-cms/auth-atproto@1619

@emdash-cms/blocks

npm i https://pkg.pr.new/@emdash-cms/blocks@1619

@emdash-cms/cloudflare

npm i https://pkg.pr.new/@emdash-cms/cloudflare@1619

@emdash-cms/contentful-to-portable-text

npm i https://pkg.pr.new/@emdash-cms/contentful-to-portable-text@1619

emdash

npm i https://pkg.pr.new/emdash@1619

create-emdash

npm i https://pkg.pr.new/create-emdash@1619

@emdash-cms/gutenberg-to-portable-text

npm i https://pkg.pr.new/@emdash-cms/gutenberg-to-portable-text@1619

@emdash-cms/plugin-cli

npm i https://pkg.pr.new/@emdash-cms/plugin-cli@1619

@emdash-cms/plugin-types

npm i https://pkg.pr.new/@emdash-cms/plugin-types@1619

@emdash-cms/registry-client

npm i https://pkg.pr.new/@emdash-cms/registry-client@1619

@emdash-cms/registry-lexicons

npm i https://pkg.pr.new/@emdash-cms/registry-lexicons@1619

@emdash-cms/sandbox-workerd

npm i https://pkg.pr.new/@emdash-cms/sandbox-workerd@1619

@emdash-cms/x402

npm i https://pkg.pr.new/@emdash-cms/x402@1619

@emdash-cms/plugin-ai-moderation

npm i https://pkg.pr.new/@emdash-cms/plugin-ai-moderation@1619

@emdash-cms/plugin-atproto

npm i https://pkg.pr.new/@emdash-cms/plugin-atproto@1619

@emdash-cms/plugin-audit-log

npm i https://pkg.pr.new/@emdash-cms/plugin-audit-log@1619

@emdash-cms/plugin-color

npm i https://pkg.pr.new/@emdash-cms/plugin-color@1619

@emdash-cms/plugin-embeds

npm i https://pkg.pr.new/@emdash-cms/plugin-embeds@1619

@emdash-cms/plugin-field-kit

npm i https://pkg.pr.new/@emdash-cms/plugin-field-kit@1619

@emdash-cms/plugin-forms

npm i https://pkg.pr.new/@emdash-cms/plugin-forms@1619

@emdash-cms/plugin-webhook-notifier

npm i https://pkg.pr.new/@emdash-cms/plugin-webhook-notifier@1619

commit: 2302e2d

@github-actions github-actions Bot added the query-count changed PR diff modifies query-count snapshot files label Jun 25, 2026
@github-actions

github-actions Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

Query-count snapshot changes

40 routes changed, total Δ -182 queries.

SQLite

Route Before After Δ
GET / (cold) 11 6 -5
GET / (warm) 11 6 -5
GET /category/development (cold) 15 10 -5
GET /category/development (warm) 14 9 -5
GET /contributors (cold) 11 6 -5
GET /contributors (warm) 11 6 -5
GET /contributors-naive (cold) 18 13 -5
GET /contributors-naive (warm) 18 13 -5
GET /pages/about (cold) 10 6 -4
GET /pages/about (warm) 10 6 -4
GET /posts (cold) 11 6 -5
GET /posts (warm) 11 6 -5
GET /posts/building-for-the-long-term (cold) 24 17 -7
GET /posts/building-for-the-long-term (warm) 24 17 -7
GET /rss.xml (cold) 5 2 -3
GET /rss.xml (warm) 5 2 -3
GET /search (cold) 12 10 -2
GET /search (warm) 12 10 -2
GET /tag/webdev (cold) 14 9 -5
GET /tag/webdev (warm) 14 9 -5

D1

Route Before After Δ
GET / (cold) 22 17 -5
GET / (warm) 11 6 -5
GET /category/development (cold) 26 21 -5
GET /category/development (warm) 14 9 -5
GET /contributors (cold) 22 17 -5
GET /contributors (warm) 11 6 -5
GET /contributors-naive (cold) 29 24 -5
GET /contributors-naive (warm) 18 13 -5
GET /pages/about (cold) 20 17 -3
GET /pages/about (warm) 10 6 -4
GET /posts (cold) 22 17 -5
GET /posts (warm) 11 6 -5
GET /posts/building-for-the-long-term (cold) 35 28 -7
GET /posts/building-for-the-long-term (warm) 24 17 -7
GET /rss.xml (cold) 15 12 -3
GET /rss.xml (warm) 5 2 -3
GET /search (cold) 22 21 -1
GET /search (warm) 12 10 -2
GET /tag/webdev (cold) 26 21 -5
GET /tag/webdev (warm) 14 9 -5

Comparing snapshot files between base and head. Updated automatically on each push.

@ascorbic

Copy link
Copy Markdown
Member Author

/review

emdashbot[bot]
emdashbot Bot previously requested changes Jun 25, 2026

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

The approach is sound: folding byline + taxonomy hydration into the content query is exactly the right tool for cutting round trips on remote databases, and the fallback path for custom byline fields / author fallback keeps the common case fast without breaking edge cases. The changeset and dialect-aware aggregation shape are good.

However, the implementation has three concrete regressions/gaps that need fixing before merge:

  1. Folded bylines drop avatarMediaId. BylineSummary requires avatarMediaId, and the existing demos read entry.data.bylines[0].byline.avatarMediaId to render author avatars. The folded JSON does not carry that column, so those avatars break. The fix is a one-column addition to the json_object/json_build_object field list.

  2. Stale SQLite query-counts snapshot. scripts/query-counts.queries.sqlite.json was updated in this PR, but the stored folded subqueries contain ORDER BY t.label ASC / ORDER BY cb.sort_order ASC clauses that foldedHydrationSelects in loader.ts does not emit (ordering is intentionally done in the consumer). scripts/query-counts.mjs compares query text exactly, so running the harness will fail. The snapshot needs to be regenerated from the current code.

  3. Folded terms no longer prime the per-entry request cache. Previously getAllTermsForEntries → primeEntryTermsCache seeded requestCached keys used by getEntryTerms. The new fast path skips that, so pages that call getEmDashCollection and then getEntryTerms(...) per entry (a common pattern) now produce an extra query per entry instead of a cache hit. The fast path should prime the same keys.

  4. Byline custom-field check swallows non-missing-table errors. If getBylineFieldDefs throws for any reason other than a missing table, the code continues as if there are no custom fields and serves folded bylines with customFields: {}, potentially silently dropping real custom-field values. It should fall back to the query path on unexpected errors.

I also recommend adding test coverage that asserts the public hydrated shape (data.bylines, data.terms, and specifically byline.avatarMediaId) rather than only the private FOLDED_* symbols, so regressions like #1 are caught by pnpm test.

Comment thread packages/core/src/loader.ts Outdated
const terms = sql`(SELECT ${agg(termObj)} FROM ${sql.ref("content_taxonomies")} AS ct JOIN ${sql.ref("taxonomies")} AS t ON t.translation_group = ct.taxonomy_id WHERE ct.collection = ${type} AND ct.entry_id = ${o}.id AND t.locale = ${o}.locale) AS ${sql.ref("_emdash_terms")}`;

const bylineInner = obj(
"'id', b.id, 'slug', b.slug, 'displayName', b.display_name, 'bio', b.bio, 'avatarStorageKey', m.storage_key, 'avatarAlt', m.alt, 'avatarBlurhash', m.blurhash, 'avatarDominantColor', m.dominant_color, 'websiteUrl', b.website_url, 'userId', b.user_id, 'isGuest', b.is_guest, 'createdAt', b.created_at, 'updatedAt', b.updated_at, 'locale', b.locale, 'translationGroup', b.translation_group",

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.

[needs fixing] The folded byline JSON is missing avatarMediaId, a required field on BylineSummary. Existing demo templates read credit.byline.avatarMediaId to render author avatar images, so this regresses live sites and is a backwards-incompatible change to the public data shape.

Add b.avatar_media_id to the inner JSON payload:

Suggested change
"'id', b.id, 'slug', b.slug, 'displayName', b.display_name, 'bio', b.bio, 'avatarStorageKey', m.storage_key, 'avatarAlt', m.alt, 'avatarBlurhash', m.blurhash, 'avatarDominantColor', m.dominant_color, 'websiteUrl', b.website_url, 'userId', b.user_id, 'isGuest', b.is_guest, 'createdAt', b.created_at, 'updatedAt', b.updated_at, 'locale', b.locale, 'translationGroup', b.translation_group",
const bylineInner = obj(
"'id', b.id, 'slug', b.slug, 'displayName', b.display_name, 'bio', b.bio, 'avatarMediaId', b.avatar_media_id, 'avatarStorageKey', m.storage_key, 'avatarAlt', m.alt, 'avatarBlurhash', m.blurhash, 'avatarDominantColor', m.dominant_color, 'websiteUrl', b.website_url, 'userId', b.user_id, 'isGuest', b.is_guest, 'createdAt', b.created_at, 'updatedAt', b.updated_at, 'locale', b.locale, 'translationGroup', b.translation_group",
);

"select * from \"_emdash_taxonomy_defs\"": 1,
"SELECT * FROM \"ec_pages\" WHERE deleted_at IS NULL AND (\"status\" = 'published' OR (\"status\" = 'scheduled' AND \"scheduled_at\" <= strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))) ORDER BY \"created_at\" DESC, \"id\" DESC": 1,
"SELECT * FROM \"ec_posts\" WHERE deleted_at IS NULL AND (\"status\" = 'published' OR (\"status\" = 'scheduled' AND \"scheduled_at\" <= strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))) ORDER BY \"published_at\" DESC, \"id\" DESC LIMIT ?": 1
"SELECT *, (SELECT json_group_array(json_object('id', t.id, 'name', t.name, 'slug', t.slug, 'label', t.label, 'parent_id', t.parent_id, 'locale', t.locale, 'translation_group', t.translation_group)) FROM \"content_taxonomies\" AS ct JOIN \"taxonomies\" AS t ON t.translation_group = ct.taxonomy_id WHERE ct.collection = ? AND ct.entry_id = \"ec_pages\".id ORDER BY t.label ASC) AS \"_emdash_terms\", (SELECT json_group_array(json_object('roleLabel', cb.role_label, 'sortOrder', cb.sort_order, 'byline', json_object('id', b.id, 'slug', b.slug, 'displayName', b.display_name, 'bio', b.bio, 'avatarStorageKey', m.storage_key, 'avatarAlt', m.alt, 'avatarBlurhash', m.blurhash, 'avatarDominantColor', m.dominant_color, 'websiteUrl', b.website_url, 'userId', b.user_id, 'isGuest', b.is_guest, 'createdAt', b.created_at, 'updatedAt', b.updated_at, 'locale', b.locale, 'translationGroup', b.translation_group))) FROM \"_emdash_content_bylines\" AS cb JOIN \"_emdash_bylines\" AS b ON b.translation_group = cb.byline_id LEFT JOIN \"media\" AS m ON m.id = b.avatar_media_id WHERE cb.collection_slug = ? AND cb.content_id = \"ec_pages\".id AND b.locale = \"ec_pages\".locale ORDER BY cb.sort_order ASC) AS \"_emdash_bylines\" FROM \"ec_pages\" WHERE deleted_at IS NULL AND (\"status\" = 'published' OR (\"status\" = 'scheduled' AND \"scheduled_at\" <= strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))) ORDER BY \"created_at\" DESC, \"id\" DESC": 1,

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.

[needs fixing] This folded subquery snapshot contains ORDER BY t.label ASC and ORDER BY cb.sort_order ASC inside the correlated subqueries, but foldedHydrationSelects in loader.ts intentionally does not apply ordering in the aggregate (the consumer sorts instead). scripts/query-counts.mjs compares SQL text exactly, so the harness will flag a mismatch.

Regenerate the SQLite query snapshot from the actual code with:

node scripts/query-counts.mjs --target sqlite --update

@@ -1005,6 +1067,37 @@ async function hydrateEntryTerms<D>(
): Promise<void> {
if (entries.length === 0) return;

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.

[needs fixing] The folded terms fast path no longer primes the per-entry request cache. The previous code path through getAllTermsForEntries called primeEntryTermsCache, which seeded the same requestCached keys that getEntryTerms uses. Without this, pages that call getEmDashCollection and then call getEntryTerms(...) per entry re-query the database for each entry.

After assigning data.terms = grouped, import setRequestCacheEntry from ./request-cache.js and prime the wildcard + per-name keys:

Suggested change
if (entries.length === 0) return;
data.terms = grouped;
// Prime the same per-entry request cache that getAllTermsForEntries
// used to populate, so subsequent getEntryTerms calls in this render
// don't issue an N+1 query.
const localeKey = locale ?? "*";
setRequestCacheEntry(
`terms:${type}:${data.id}:*:${localeKey}`,
Object.values(grouped).flat(),
);
for (const [name, terms] of Object.entries(grouped)) {
setRequestCacheEntry(`terms:${type}:${data.id}:${name}:${localeKey}`, terms);
}

// skips, or the author-fallback path which the fold doesn't express.
const needsQueryPath = parsed.some(
(p) =>
p.credits.length === 0 &&

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.

[needs fixing] The custom-field probe catches all errors and treats them as "no custom fields". If getBylineFieldDefs throws for any reason other than a missing table, the fold still emits customFields: {}, which can silently drop real custom-field values.

Change needsQueryPath to let and fall back to the query path on unexpected errors:

Suggested change
p.credits.length === 0 &&
let needsQueryPath = parsed.some(
(p) =>
p.credits.length === 0 &&
(dataStr(p.data, "authorId") !== "" || dataStr(p.data, "primaryBylineId") !== ""),
);
let hasCustomFields = false;
if (!needsQueryPath) {
try {
const { getDb } = await import("./loader.js");
const db = await getDb();
const { getBylineFieldDefs } = await import("./bylines/field-defs-cache.js");
hasCustomFields = (await getBylineFieldDefs(db)).length > 0;
} catch (error) {
// Missing tables are expected during pre-migration warmups. Any
// other error means we can't trust the probe, so fall back to the
// query path rather than risk serving empty customFields.
if (!isMissingTableError(error)) {
needsQueryPath = true;
}
}
}

@github-actions github-actions Bot added review/awaiting-author Reviewed; waiting on the author to respond and removed review/needs-review No maintainer or bot review yet labels Jun 25, 2026
ask-bonk[bot]
ask-bonk Bot previously requested changes Jun 25, 2026
Comment thread packages/core/src/loader.ts Outdated
const terms = sql`(SELECT ${agg(termObj)} FROM ${sql.ref("content_taxonomies")} AS ct JOIN ${sql.ref("taxonomies")} AS t ON t.translation_group = ct.taxonomy_id WHERE ct.collection = ${type} AND ct.entry_id = ${o}.id AND t.locale = ${o}.locale) AS ${sql.ref("_emdash_terms")}`;

const bylineInner = obj(
"'id', b.id, 'slug', b.slug, 'displayName', b.display_name, 'bio', b.bio, 'avatarStorageKey', m.storage_key, 'avatarAlt', m.alt, 'avatarBlurhash', m.blurhash, 'avatarDominantColor', m.dominant_color, 'websiteUrl', b.website_url, 'userId', b.user_id, 'isGuest', b.is_guest, 'createdAt', b.created_at, 'updatedAt', b.updated_at, 'locale', b.locale, 'translationGroup', b.translation_group",

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.

[regression] Confirmed: the folded byline JSON omits avatar_media_id, but avatarMediaId: string | null is a required field on BylineSummary (packages/core/src/database/repositories/types.ts:61) and is read directly by templates to render author avatars:

demos/cloudflare/src/components/PostCard.astro:55:    {credit.byline.avatarMediaId && (
demos/cloudflare/src/pages/posts/[slug].astro:142:    {credit.byline.avatarMediaId && (
demos/cloudflare/src/pages/posts/index.astro:63:    {credit.byline.avatarMediaId && (
demos/cloudflare/src/pages/index.astro:106:    {credit.byline.avatarMediaId && (
demos/simple/src/components/PostCard.astro:55:    {credit.byline.avatarMediaId && (

On the fast path, byline.avatarMediaId becomes undefined, so && <img …> is falsy and avatars stop rendering on every site using this pattern. This is a backwards-incompatible change to the public hydrated shape.

Fix: add 'avatarMediaId', b.avatar_media_id to the inner JSON payload.

"select * from \"_emdash_taxonomy_defs\"": 1,
"SELECT * FROM \"ec_pages\" WHERE deleted_at IS NULL AND (\"status\" = 'published' OR (\"status\" = 'scheduled' AND \"scheduled_at\" <= strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))) ORDER BY \"created_at\" DESC, \"id\" DESC": 1,
"SELECT * FROM \"ec_posts\" WHERE deleted_at IS NULL AND (\"status\" = 'published' OR (\"status\" = 'scheduled' AND \"scheduled_at\" <= strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))) ORDER BY \"published_at\" DESC, \"id\" DESC LIMIT ?": 1
"SELECT *, (SELECT json_group_array(json_object('id', t.id, 'name', t.name, 'slug', t.slug, 'label', t.label, 'parent_id', t.parent_id, 'locale', t.locale, 'translation_group', t.translation_group)) FROM \"content_taxonomies\" AS ct JOIN \"taxonomies\" AS t ON t.translation_group = ct.taxonomy_id WHERE ct.collection = ? AND ct.entry_id = \"ec_pages\".id ORDER BY t.label ASC) AS \"_emdash_terms\", (SELECT json_group_array(json_object('roleLabel', cb.role_label, 'sortOrder', cb.sort_order, 'byline', json_object('id', b.id, 'slug', b.slug, 'displayName', b.display_name, 'bio', b.bio, 'avatarStorageKey', m.storage_key, 'avatarAlt', m.alt, 'avatarBlurhash', m.blurhash, 'avatarDominantColor', m.dominant_color, 'websiteUrl', b.website_url, 'userId', b.user_id, 'isGuest', b.is_guest, 'createdAt', b.created_at, 'updatedAt', b.updated_at, 'locale', b.locale, 'translationGroup', b.translation_group))) FROM \"_emdash_content_bylines\" AS cb JOIN \"_emdash_bylines\" AS b ON b.translation_group = cb.byline_id LEFT JOIN \"media\" AS m ON m.id = b.avatar_media_id WHERE cb.collection_slug = ? AND cb.content_id = \"ec_pages\".id AND b.locale = \"ec_pages\".locale ORDER BY cb.sort_order ASC) AS \"_emdash_bylines\" FROM \"ec_pages\" WHERE deleted_at IS NULL AND (\"status\" = 'published' OR (\"status\" = 'scheduled' AND \"scheduled_at\" <= strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))) ORDER BY \"created_at\" DESC, \"id\" DESC": 1,

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.

[regression] Confirmed: this snapshot does not match what foldedHydrationSelects in loader.ts actually emits. Two divergences:

  1. The snapshot contains ORDER BY t.label ASC (40 occurrences) and ORDER BY cb.sort_order ASC inside the correlated subqueries; the current code intentionally omits them (consumer sorts).
  2. The snapshot lacks the AND t.locale = "<entry>.locale" correlation that loader.ts:111 emits as part of the getEmDashEntry/getEmDashCollection hydrate taxonomy terms using request/default locale instead of explicit query locale #1441 fix (only the byline-side b.locale correlation is in the snapshot).

These look like artefacts of generating the snapshot against an earlier revision that had in-aggregate ordering and no term-locale correlation. scripts/query-counts.mjs:471 compares query text exactly, so the harness will fail on pnpm query-counts.

Regenerate with node scripts/query-counts.mjs --target sqlite --update.

for (const [name, arr] of Object.entries(grouped)) {
grouped[name] = arr.toSorted((a, b) => String(a.label).localeCompare(String(b.label)));
}
data.terms = grouped;

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 regression] Confirmed: the folded-terms fast path drops the per-entry request-cache priming that getAllTermsForEntries → primeEntryTermsCache did (packages/core/src/taxonomies/index.ts:585-603). It seeded the same requestCached keys that getEntryTerms uses (packages/core/src/taxonomies/index.ts:310-311), including empty arrays for taxonomies that apply to the collection but have no rows on this entry — which short-circuited getEntryTerms(collection, id, "category") to a cached [] instead of a DB hit.

A template that does getEmDashCollection("posts") then loops and calls getEntryTerms(post.data.id, "category") per entry now produces N extra queries per render where it used to produce 0 — turning a perf-win PR into an N+1 regression for that pattern.

After data.terms = grouped, prime both the wildcard key and the per-name keys (and ideally seed [] for applicableTaxonomyNames not present in grouped, to match the old behaviour exactly):

const localeKey = locale ?? "*";
setRequestCacheEntry(
  `terms:${type}:${data.id}:*:${localeKey}`,
  Object.values(grouped).flat(),
);
for (const [name, terms] of Object.entries(grouped)) {
  setRequestCacheEntry(`terms:${type}:${data.id}:${name}:${localeKey}`, terms);
}

hasCustomFields = (await getBylineFieldDefs(db)).length > 0;
} catch {
// Treat as no custom fields; the fold's values are still correct.
}

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.

[correctness] Confirmed: this catch swallows every error from getBylineFieldDefs and treats it as "no custom fields registered", which then serves folded bylines with customFields: {} — silently dropping real custom-field values when a transient/unexpected error occurs (lock-init failure, dialect error, etc.). getBylineFieldDefs has a fairly involved init path with a lock and two-tier cache (packages/core/src/bylines/field-defs-cache.ts:127), so non-missing-table failures are not purely theoretical.

The missing-table case is the only one the old query path silently absorbed — every other failure should fall back to the query path rather than risk a stale-shape response:

let needsQueryPath = parsed.some(/* …existing… */);
let hasCustomFields = false;
if (!needsQueryPath) {
  try {
    const { getDb } = await import("./loader.js");
    const db = await getDb();
    const { getBylineFieldDefs } = await import("./bylines/field-defs-cache.js");
    hasCustomFields = (await getBylineFieldDefs(db)).length > 0;
  } catch (error) {
    if (!isMissingTableError(error)) needsQueryPath = true;
  }
}

expect(credits).toHaveLength(1);
expect(credits[0]!.roleLabel).toBe("Author");
expect(credits[0]!.byline.displayName).toBe("Ada Lovelace");
});

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.

[test gap] These tests assert the private FOLDED_BYLINES / FOLDED_TERMS symbol payloads but never the public hydrated shape that consumers actually read (entry.data.bylines[i].byline.avatarMediaId, entry.data.terms[name]). The avatarMediaId-drop regression (see loader.ts:114) escapes the suite specifically because nothing here calls getEmDashEntry / getEmDashCollection and reads .data.bylines.

Adding one assertion at this layer — e.g. seed a byline with an avatarMediaId, fetch via getEmDashEntry, expect entry.data.bylines[0].byline.avatarMediaId === <id> — would have caught the regression and would catch the next one of the same shape.

@ask-bonk

ask-bonk Bot commented Jun 25, 2026

Copy link
Copy Markdown
Contributor

Review posted successfully (CHANGES_REQUESTED with 5 line-anchored comments).

Summary of the review I posted on PR #1619:

Independently verified all four findings from the prior emdashbot review:

  1. loader.ts:114 — avatar regression (HIGH): The folded byline JSON drops avatar_media_id. BylineSummary.avatarMediaId is a required field, and four demo templates (demos/cloudflare/**, demos/simple/**) read credit.byline.avatarMediaId to render avatars. Templates will silently stop rendering avatars on every site using this pattern.

  2. scripts/query-counts.queries.sqlite.json:7 — stale snapshot (HIGH): Two divergences from the actual SQL emitted by foldedHydrationSelects: spurious ORDER BY t.label ASC / ORDER BY cb.sort_order ASC clauses in 40 places, AND missing AND t.locale = <entry>.locale correlation (the getEmDashEntry/getEmDashCollection hydrate taxonomy terms using request/default locale instead of explicit query locale #1441 fix). The query-counts harness compares text exactly and will fail.

  3. query.ts:1096 — N+1 regression (MEDIUM): Fast path drops primeEntryTermsCache, so any template doing getEmDashCollection + per-entry getEntryTerms(...) re-queries the DB per entry instead of hitting the request cache.

  4. query.ts:982 — error swallowing (MEDIUM): Bare catch on getBylineFieldDefs swallows non-missing-table errors and serves folded bylines with customFields: {}, potentially dropping real custom-field values on transient failures.

Added one fresh observation:

  1. tests/integration/loader-fold.test.ts:108 — test gap: Tests assert the private symbol payloads but never the public hydrated shape that consumers read (entry.data.bylines[i].byline.avatarMediaId, entry.data.terms). This is why the avatarMediaId regression escaped — a single end-to-end assertion through getEmDashEntry would have caught it.

Review URL: #1619 (review)

github run

- Carry avatarMediaId in the folded byline JSON; it is a required
  BylineSummary field templates read to render author avatars, so the
  fold dropping it broke avatars on the fast path.
- Fall back to the byline query path when the custom-field probe throws
  a non-missing-table error, instead of serving folded bylines with
  empty customFields.
- Prime the per-entry term request cache from the folded-terms fast path
  (new primeFoldedEntryTerms helper), so subsequent getEntryTerms calls
  hit the cache instead of issuing an N+1 query.
- Regenerate the SQLite query-counts snapshot to match the emitted SQL.
- Add a public-shape test (avatarMediaId, term-cache priming).
@github-actions github-actions Bot added review/needs-rereview New commits since the last review and removed review/awaiting-author Reviewed; waiting on the author to respond labels Jun 25, 2026
@ascorbic

Copy link
Copy Markdown
Member Author

Addressed all four review findings in 12c6e95:

  1. avatarMediaId dropped — added 'avatarMediaId', b.avatar_media_id to the folded byline JSON (loader.ts). Templates read credit.byline.avatarMediaId to render avatars, so this restores the public shape on the fast path.

  2. Stale SQLite query-counts snapshot — regenerated with node scripts/query-counts.mjs --target sqlite --update. Both query-counts.snapshot.sqlite.json and .queries.sqlite.json now match the emitted SQL (no ORDER BY in the aggregate, term-locale correlation present). pnpm query-counts passes. Net vs main is a clear reduction everywhere (article 24->16, index 11->7); the previously committed snapshot was the earlier-revision artifact you flagged. Changeset numbers updated to match (16/7).

  3. Folded terms didn't prime the request cache — the fast path now calls a new primeFoldedEntryTerms helper (exported from taxonomies/index.ts) that reuses primeEntryTermsCache, so it seeds the exact same wildcard + per-name keys (including [] for applicable taxonomies absent from the entry) as getAllTermsForEntries. Subsequent getEntryTerms calls hit the cache. Keeping the key logic in the taxonomies module avoids drift.

  4. Byline probe swallowed non-missing-table errors — needsQueryPath is now let; on any error other than a missing table the probe falls back to the query path rather than serving customFields: {}.

Plus the requested public-shape coverage: query-fold-public-shape.test.ts asserts data.bylines[0].byline.avatarMediaId via getEmDashEntry, and that folded terms prime the cache (it seeds a term absent from content_taxonomies and confirms getEntryTerms still returns it). The loader-fold integration test also now seeds an avatar and asserts it survives the fold.

Lint clean, typecheck passes, all 4111 core tests pass, formatted.

emdashbot Bot and others added 3 commits June 25, 2026 09:43
The previous priming seeded [] for taxonomies applicable to the
collection but absent from the entry, which required a getTaxonomyDefs
query on every fold render. That added one round trip to routes that
never call getEntryTerms for an absent taxonomy (contributors, about,
rss, search), eroding the fold's win.

Prime only the wildcard and present-taxonomy keys, straight from the
folded data with no DB lookup. getEntryTerms(id, absentTaxonomy) falls
through to its own cached query instead, which is the rarer case.
@ascorbic

Copy link
Copy Markdown
Member Author

Follow-up on the query-count diff (thanks for catching this):

/contributors-naive going 6→13 (SQLite) / 6→14 (D1) is correct, not a regression. That fixture route does a per-avatar mediaRepo.findById(credit.byline.avatarMediaId). The original fold dropped avatarMediaId, so mediaId was undefined and every avatar lookup silently no-op'd — the route wasn't doing the work it exists to measure. Restoring avatarMediaId means those lookups run again, so the count legitimately rises. (That's exactly the cost the /contributors JOIN is meant to remove.)

The +1 my priming added to /contributors, /pages/about, /rss, /search was a real regression, now fixed (030a15b). The priming was seeding [] for taxonomies applicable-but-absent on the entry, which needed a getTaxonomyDefs query every fold render. I dropped that: priming now seeds only the wildcard + present-taxonomy keys straight from the folded data, no DB lookup. getEntryTerms(id, absentTaxonomy) falls through to its own cached query (the rarer case).

Net vs main is back to a clean reduction everywhere — index 11→6, article 24→17, /contributors 11→6, etc. The only route that rises vs the prior fold snapshot is contributors-naive, for the avatarMediaId reason above. CI will regenerate the D1 snapshot on this push.

emdashbot Bot and others added 2 commits June 25, 2026 10:02
The D1 query-text snapshot was last written in #1580 and still showed
the pre-fold path (separate byline and term queries). CI regenerates it
but only commits the count snapshots, so it never got refreshed. Counts
are unchanged; this just updates the recorded SQL to the folded query.
@ascorbic ascorbic added the bot:review Trigger an emdashbot code review on this PR label Jun 25, 2026
@ascorbic

Copy link
Copy Markdown
Member Author

/review

@ask-bonk

ask-bonk Bot commented Jun 25, 2026

Copy link
Copy Markdown
Contributor

OK looks clean. Now one final concern I want to verify — what happens when the entries array has FOLDED_TERMS but the entry has data.id = ""? entryId = "" → skipped from perEntry. Priming still occurs for entries with valid IDs. But data.terms = grouped is set on the empty-id entry anyway. Fine.

Now let me consider — the prime is called with locale passed from caller. If locale === undefined (i18n disabled), resolveLocale(undefined) returns... let me check resolveLocale:

if (explicit !== undefined) return explicit; — undefined skipped.
const ctxLocale = getRequestContext()?.locale; — could be undefined.
if (cfg && isI18nEnabled()) return cfg.defaultLocale; — only if i18n enabled.

So resolveLocale(undefined) with i18n DISABLED returns undefined. The prime keys things at undefined ?? "*" = "*". getEntryTerms called later also computes resolveLocale() → undefined → "*". Cache hit. ✓

In my final assessment, the code looks correct. The previous review caught the major issues, and the author addressed them. My adversarial pass didn't surface critical bugs.

Let me decide what to comment on. Per the skill: silence = approval. The issues I found are minor optimizations, not bugs:

  1. Preview/revision path doesn't stashFolded → minor inefficiency, not a bug
  2. localeCompare vs BINARY ordering → behavior shift but not incorrect

Neither is severe enough to warrant a comment.

Per the task instructions: "If the PR looks good, respond with only 'LGTM!' and skip posting a review."

Given the prior thorough review caught real bugs, the author addressed them properly with verification, and my adversarial pass didn't surface new bugs of meaningful severity, this PR is in good shape.

LGTM!

github run

@ascorbic
ascorbic dismissed stale reviews from ask-bonk[bot] and emdashbot[bot] June 25, 2026 12:13

Fixed

@github-actions github-actions Bot added review/needs-review No maintainer or bot review yet and removed review/needs-rereview New commits since the last review labels Jun 25, 2026
@ascorbic
ascorbic merged commit c056060 into main Jun 25, 2026
70 of 73 checks passed
@ascorbic
ascorbic deleted the perf/fold-hydration-into-content branch June 25, 2026 12:22
@emdashbot emdashbot Bot mentioned this pull request Jun 25, 2026
ascorbic pushed a commit that referenced this pull request Jun 27, 2026
…archives (#1364) (#1577)

* fix(core): add offset pagination to getEmDashCollection for numbered archives (#1364)

getEmDashCollection only supported cursor/keyset pagination, so numbered
archive routes (/page/2, /tag/security/page/3) had to either walk cursors
page by page or over-fetch from the start and slice — fetching up to 1,000
rows to render 20 on /page/50.

Add an `offset` option to the public CollectionFilter and the loader filter,
applied as a SQL OFFSET (cross-dialect: SQLite needs a LIMIT, so a bare
offset uses LIMIT -1; Postgres takes a standalone OFFSET). Offset and cursor
are mutually exclusive — cursor (keyset) wins when both are set so they don't
stack into a double skip. Only a positive integer applies.

Also surface `hasMore` on CollectionResult whenever a limit is set, computed
from the existing over-fetch-by-one, so archive routes can render a next-page
link without an extra count query. Offset calls bypass limit bucketing (their
limit is part of the pagination contract) and the offset is part of the
request-cache key so distinct pages don't collide.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* test(core): rename offset cache-key test to match its assertion (#1364)

The test verifies that offset IS part of the request-cache key (so
numbered-archive pages don't collide), but its name read as the inverse.
Rename to match the behavior, per PR review.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* refactor(core): make CollectionFilter a cursor/offset discriminated union (#1364)

cursor and offset are mutually exclusive ways to express "the next page",
but as two optional properties on one interface, supplying both compiled
fine and silently relied on the runtime "cursor wins" fallback. Split the
filter into a shared CollectionFilterBase plus CursorCollectionFilter and
OffsetCollectionFilter variants, and export CollectionFilter as their
union, in both the public query API and the loader filter — so passing
both is now a compile-time error.

The query->loader mapping spreads only the active pagination key (cursor
wins) rather than emitting both, so the literal still satisfies the union.
Adds a compile-time test asserting the both-at-once case is rejected.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(core): thread hasMore through the L2 collection cache snapshot

Rebasing onto main surfaced a gap: #1619 introduced a cached snapshot
layer (loadCollectionCached / CachedCollectionValue) that round-trips
collection results but did not carry the `hasMore` flag this PR adds.
Offset-paginated callers therefore saw `hasMore: undefined` instead of
the over-fetch-derived boolean. Persist and revive `hasMore` in the
snapshot so numbered-archive pages get a correct final-page signal.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/core bot:review Trigger an emdashbot code review on this PR cla: signed query-count changed PR diff modifies query-count snapshot files review/needs-review No maintainer or bot review yet size/XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant