-
Notifications
You must be signed in to change notification settings - Fork 1.1k
fix: skip byline query path when the bylines table is empty #2304
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
edrpls
wants to merge
3
commits into
emdash-cms:main
Choose a base branch
from
edrpls:fix/byline-hydration-empty-table
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| "emdash": patch | ||
| --- | ||
|
|
||
| Fixes sites that don't use bylines paying dead byline lookup queries on every content read. When the bylines table is empty, entries with an author no longer send hydration down the byline query path — the folded result is served directly, removing the wasted round trips from anonymous page renders. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
138 changes: 138 additions & 0 deletions
138
packages/core/tests/unit/bylines/hydration-empty-table.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,138 @@ | ||
| /** | ||
| * Byline hydration on sites with no bylines. | ||
| * | ||
| * When `_emdash_bylines` is empty, the folded byline JSON is authoritative: | ||
| * no credit can exist in any locale and the author fallback has no byline to | ||
| * resolve to. Entries that merely have an `author_id` must not send the | ||
| * batch down the byline query path — those lookups can only return zero | ||
| * rows, and they run on every logged-out render. Once a byline row exists, | ||
| * the author fallback must still take the query path. | ||
| */ | ||
|
|
||
| import BetterSqlite3 from "better-sqlite3"; | ||
| import { Kysely, SqliteDialect } from "kysely"; | ||
| import { afterEach, describe, expect, it, vi } from "vitest"; | ||
|
|
||
| import { runMigrations } from "../../../src/database/migrations/runner.js"; | ||
| import { BylineRepository } from "../../../src/database/repositories/byline.js"; | ||
| import { ContentRepository } from "../../../src/database/repositories/content.js"; | ||
| import type { Database } from "../../../src/database/types.js"; | ||
| import { emdashLoader } from "../../../src/loader.js"; | ||
| import { getEmDashCollection } from "../../../src/query.js"; | ||
| import { runWithContext } from "../../../src/request-context.js"; | ||
| import { SchemaRegistry } from "../../../src/schema/registry.js"; | ||
|
|
||
| vi.mock("astro:content", () => ({ | ||
| getLiveCollection: vi.fn(), | ||
| getLiveEntry: vi.fn(), | ||
| })); | ||
|
|
||
| import { getLiveCollection } from "astro:content"; | ||
|
|
||
| const openDbs: Kysely<Database>[] = []; | ||
|
|
||
| /** | ||
| * In-memory db with a query counter on Kysely's `log` hook, so the tests can | ||
| * assert "no byline query was issued" against real SQL (no repository mocks). | ||
| */ | ||
| async function setupCountingDb(): Promise<{ | ||
| db: Kysely<Database>; | ||
| queries: string[]; | ||
| reset: () => void; | ||
| }> { | ||
| const sqlite = new BetterSqlite3(":memory:"); | ||
| const queries: string[] = []; | ||
| const db = new Kysely<Database>({ | ||
| dialect: new SqliteDialect({ database: sqlite }), | ||
| log: (event) => { | ||
| if (event.level === "query") queries.push(event.query.sql); | ||
| }, | ||
| }); | ||
| openDbs.push(db); | ||
| await runMigrations(db); | ||
| const registry = new SchemaRegistry(db); | ||
| await registry.createCollection({ slug: "post", label: "Posts", labelSingular: "Post" }); | ||
| await registry.createField("post", { slug: "title", label: "Title", type: "string" }); | ||
| return { db, queries, reset: () => queries.splice(0, queries.length) }; | ||
| } | ||
|
|
||
| /** Route getLiveCollection through the real loader so folded columns flow. */ | ||
| function delegateToLoader() { | ||
| const loader = emdashLoader(); | ||
| vi.mocked(getLiveCollection).mockImplementation(async (_name: string, filter: unknown) => | ||
| // eslint-disable-next-line typescript/no-explicit-any -- loader filter is a runtime-validated union | ||
| loader.loadCollection!({ filter: filter as any }), | ||
| ); | ||
| } | ||
|
|
||
| /** Byline lookups issued by the query path (the folded content SELECT reads | ||
| * the byline tables too, but only inside the `ec_post` query). */ | ||
| function bylineQueries(queries: string[]): string[] { | ||
| return queries.filter( | ||
| (q) => | ||
| !q.includes("ec_post") && | ||
| (q.includes("_emdash_content_bylines") || q.includes(`"_emdash_bylines"`)), | ||
| ); | ||
| } | ||
|
|
||
| describe("byline hydration with an empty bylines table", () => { | ||
| afterEach(async () => { | ||
| vi.mocked(getLiveCollection).mockReset(); | ||
| for (const db of openDbs.splice(0)) { | ||
| await db.destroy(); | ||
| } | ||
| }); | ||
|
|
||
| it("skips the byline query path for authored entries when no bylines exist", async () => { | ||
| const { db, queries, reset } = await setupCountingDb(); | ||
| const repo = new ContentRepository(db); | ||
| await repo.create({ | ||
| type: "post", | ||
| slug: "authored", | ||
| data: { title: "Authored Post" }, | ||
| status: "published", | ||
| authorId: "user-1", | ||
| }); | ||
| delegateToLoader(); | ||
|
|
||
| const entries = await runWithContext({ editMode: false, db }, async () => { | ||
| reset(); | ||
| const result = await getEmDashCollection("post", { status: "published" }); | ||
| return result.entries; | ||
| }); | ||
|
|
||
| expect(entries).toHaveLength(1); | ||
| const data = entries[0]!.data as Record<string, unknown>; | ||
| expect(data.bylines).toEqual([]); | ||
| expect(data.byline).toBeNull(); | ||
| expect(bylineQueries(queries)).toEqual([]); | ||
| }); | ||
|
|
||
| it("still resolves the author fallback through the query path when a byline exists", async () => { | ||
| const { db } = await setupCountingDb(); | ||
| await db | ||
| .insertInto("users") | ||
| .values({ id: "user-1", email: "ada@example.com", name: "Ada" }) | ||
| .execute(); | ||
| const bylineRepo = new BylineRepository(db); | ||
| await bylineRepo.create({ slug: "ada", displayName: "Ada Lovelace", userId: "user-1" }); | ||
| const repo = new ContentRepository(db); | ||
| await repo.create({ | ||
| type: "post", | ||
| slug: "authored-with-byline", | ||
| data: { title: "Authored Post" }, | ||
| status: "published", | ||
| authorId: "user-1", | ||
| }); | ||
| delegateToLoader(); | ||
|
|
||
| const entries = await runWithContext({ editMode: false, db }, async () => { | ||
| const result = await getEmDashCollection("post", { status: "published" }); | ||
| return result.entries; | ||
| }); | ||
|
|
||
| expect(entries).toHaveLength(1); | ||
| const data = entries[0]!.data as { byline?: { displayName?: string } | null }; | ||
| expect(data.byline?.displayName).toBe("Ada Lovelace"); | ||
| }); | ||
| }); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[needs fixing] Adds
(SELECT 1 FROM _emdash_bylines LIMIT 1)as a folded existence probe.AGENTS.mdstates: "Don't add aSELECT id FROM foo LIMIT 1to skip work on empty sites — on live sites you pay the extra query every request for no gain." This pattern matches that rule verbatim. While the PR reasonably folds it into the existing SELECT to avoid an extra round trip, the guideline as written prohibits any such probe. Please either updateAGENTS.mdto explicitly permit same-statement existence probes when they reduce total queries, or find a different mechanism (for example, a cheap per-epoch/bylines count cached at the loader level) that does not add aLIMIT 1probe to every logged-out content fetch.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fair reading of the rule as written. I've amended
AGENTS.mdin this PR to carve out the same-statement shape explicitly: the rule's cost rationale (an extra round trip on every live request) doesn't apply to an uncorrelated scalar subquery folded into a select list the request already runs — SQLite and Postgres both evaluate it once per statement. The CI query-count snapshots on this PR confirm the shape: the recorded query texts changed, the per-route counts did not.The alternative (a per-epoch cached count) was considered and rejected: it pays a real per-request
optionsread on the query path and needs cross-isolate invalidation wiring on byline creation, which is strictly worse than a zero-round-trip probe with no invalidation at all. Happy to adjust the AGENTS.md wording if maintainers prefer different phrasing.