Files
webstudio/packages/content-engine/src/document-graph/document-resolution.test.ts
T
Oleg Isonen c44ef705cf perf: Speed up Builder resource loading (#6011)
## Problem

Assets-backed Builder pages can take 6–7 seconds to become usable even
when their Assets resources only request metadata. On the
production-derived Blog project, a single Assets query measured 8,703 ms
and an immediate repeat measured 8,110 ms. Four sibling Assets resources
repeated the same authorization, development-build load/parse,
compilation, canonical-asset preparation, runtime metadata load, and
document work.

## Architecture

The loader now treats remote resources holistically while preserving
provider boundaries:

- The client scheduler is resource-provider neutral. It versions logical
requests, frees capacity when obsolete requests are replaced, ignores
stale results, and aborts physical batches only when every member is
obsolete.
- Ordinary Assets requests in one server resource-loader call use a
deferred Assets provider and execute as one repository batch.
Independent HTTP, GraphQL, and other resources start immediately instead
of waiting for Assets preparation.
- Arbitrary remote responses are **not** coalesced or persistently
cached. Their auth headers, cookies, upstream freshness, and `Vary`
semantics remain isolated.
- The Assets provider authorizes and creates its API context once per
batch, then loads only `props`, `dataSources`, and `resources` from the
development Build.
- Queries covered by the saved Build compilation plan reuse that exact
plan/artifact, preserving published byte limits, truncation, and
pinned-revision behavior. Uncovered unpinned queries use a deterministic
literal union and safely fall back to their existing individual path if
shared preparation cannot preserve behavior.
- Request-scoped document loading uses npm's byte-bounded `lru-cache` so
sibling queries do not reread the same referenced author/content files.
- Sibling dynamic queries with the same filter, sort, output, and
content shape stitch into one document-graph resolution while keeping
filter values, pagination windows, results, and failures independent.
Aggregate document/byte-limit failures fall back to isolated execution.
- Provider-neutral batching lives in the SDK runtime, and project
asset-query preview orchestration lives in the shared project package so
Builder and MCP paths can reuse the same behavior.
- Cancellation flows from the client batch through the
SDK/server/build/query path, with checkpoints between expensive phases.
- Runtime asset metadata remains conservatively artifact-wide because
URL/size filters, structured references, markdown hydration,
materialized rows, and saved plans have different reachability rules. To
make 1,000-asset artifacts safe, PostgREST `.in(...)` lookups are
deduplicated and split into 100-ID chunks with bounded concurrency.

## Implementation checklist

- [x] Trace the production Blog resource path and identify repeated work
- [x] Copy the production Blog project into an ignored disposable local
project
- [x] Record production and local baselines
- [x] Add provider-neutral client scheduling, stale-result protection,
and cancellation
- [x] Batch ordinary Assets queries without coupling or caching
HTTP/GraphQL responses
- [x] Load only Build fields required to create the saved content
compilation plan
- [x] Preserve saved-plan, truncation, fallback, diagnostics, and
revision semantics
- [x] Share Assets artifacts, runtime metadata, and revision-keyed
document reads per request
- [x] Stitch compatible query shapes into one graph resolution with
isolated fallback
- [x] Extract reusable SDK batching and project preview orchestration
for MCP/runtime consumers
- [x] Bound large runtime asset metadata lookups for the 1,000-asset
project limit
- [x] Add regression coverage and demonstrate new tests failing before
their fixes
- [x] Run focused and broad tests, type checks, lint, format,
package-boundary, and diff checks
- [x] Review documentation impact; no authoritative `docs/` content
changes are required
- [x] Regenerate and verify the affected asset-query runtime fixture; no
production data is changed
- [x] Address all actionable PR review comments
- [x] Rerun the final parity-preserving implementation against the
copied Blog project

## Measurements

Production trace before the change:

- Updates Assets query: 8,703 ms
- Immediate identical repeat: 8,110 ms
- Query artifact: 9,344 bytes / 7 documents
- Saved source database: 42,086 bytes / 28 documents

Copied-project local baseline:

- Builder navigation until resource loading: 5,111 ms
- Exact four-resource batches: 1,448 / 797 / 1,377 / 774 / 3,018 ms

During implementation, before the final saved-plan parity tightening:

- Exact four-resource batch: 174 ms first run, then 51–80 ms
- Actual Builder resource-loader requests: 234–246 ms

Final parity-preserving copied-project rerun:

- Preflight: 10 ms
- Exact four-resource batch: 435 ms cold, then 119 / 97 / 90 / 79 ms
warm
- Every response returned HTTP 200 with the same 16,884-byte payload

The final cold batch is 70% faster than the best copied-project cold
baseline, and the fastest warm batch is 90% faster than the best warm
baseline. The production trace remains the authoritative production
baseline; these before/after comparisons use the same disposable local
project and captured request payload.

## Verification

Passed:

- Full package suites: Builder (212 files / 2,496 tests), asset-uploader
(22 / 193), content-engine (40 / 274), project (7 / 84), SDK (29 / 508),
and project-build (82 / 2,070)
- Final focused regressions: Builder preview/API/resource integration (3
files / 42 tests), SDK resource loader (23 tests), and document-graph
resolution (6 tests)
- Builder, asset-uploader, content-engine, project, SDK, and
project-build type checks
- Fixture regeneration is deterministic; the generated vendor exactly
matches the source runtime bundle
- Fixture typecheck and production build
- Changed-file Oxfmt, repository Oxlint, and package-boundary checks
- `git diff --check`
- `git diff --name-only HEAD --exit-code`

New behavioral tests were demonstrated to fail before implementation and
pass afterward, including Assets batch coordination, saved-plan wiring,
truncation and pinned revisions, shared document reads, cancellation
checkpoints, stale/replaced client requests, and large PostgREST ID
filters.

Agent evaluations were not run because they require separate explicit
approval.

## Compatibility and remaining work

The public resource result/error shape and on-demand diagnostics
contract stay compatible. Generic HTTP/GraphQL caching semantics are
unchanged. Compilation already in progress is not force-cancelled
because safely interrupting shared compilation requires
ownership/reference tracking; cancellation prevents later phases from
starting.

Closes #6003
2026-08-04 18:39:41 +02:00

490 lines
13 KiB
TypeScript

import { describe, expect, test, vi } from "vitest";
import { createDocumentGraph } from "./graph";
import {
createDocumentResolutionSession,
resolveAdaptedDocumentGraph,
} from "./document-resolution";
const graph = createDocumentGraph({
nodes: [
{ id: "post", revision: "post-r1", contentRef: "content:post" },
{ id: "author", revision: "author-r1", contentRef: "content:author" },
{ id: "avatar", revision: "avatar-r1", contentRef: "content:avatar" },
],
edges: [
{
sourceId: "post",
referenceId: "#/author",
reference: {
documentId: "author",
revision: "author-r1",
representation: { type: "markdown-frontmatter" },
},
},
{
sourceId: "post",
referenceId: "#/bio",
reference: {
documentId: "author",
revision: "author-r1",
representation: { type: "markdown-body" },
},
},
{
sourceId: "author",
referenceId: "#frontmatter/avatar",
reference: {
documentId: "avatar",
revision: "avatar-r1",
representation: { type: "json", path: ["url"] },
},
},
],
});
describe("adapted document graph resolution", () => {
test("parses once and assembles nested shared cross-format references", async () => {
const sources = new Map([
[
"content:post",
{
format: "json" as const,
revision: "post-r1",
source:
'{"title":"Hello","author":{"$ref":"./author.md#frontmatter"},"bio":{"$ref":"./author.md#body"}}',
},
],
[
"content:author",
{
format: "markdown" as const,
revision: "author-r1",
source:
"---\nname: Ada\navatar:\n $ref: ./avatar.json#/url\n---\nWrites about the web.\n",
},
],
[
"content:avatar",
{
format: "json" as const,
revision: "avatar-r1",
source: '{"url":"/ada.png"}',
},
],
]);
const loaded: string[] = [];
const result = await resolveAdaptedDocumentGraph({
graph,
rootIds: ["post"],
concurrency: 3,
load: async (node) => {
loaded.push(node.contentRef);
const source = sources.get(node.contentRef);
if (source === undefined) {
throw new Error("missing fixture source");
}
return source;
},
});
expect(loaded.sort()).toEqual([...sources.keys()].sort());
expect(result.roots).toEqual([
{
format: "json",
value: {
title: "Hello",
author: { name: "Ada", avatar: "/ada.png" },
bio: "Writes about the web.\n",
},
},
]);
expect(result.values.get("author")).toMatchObject({
format: "markdown",
value: { frontmatter: { name: "Ada", avatar: "/ada.png" } },
});
});
test("applies the byte limit while loading document sources", async () => {
await expect(
resolveAdaptedDocumentGraph({
graph: createDocumentGraph({
nodes: [
{ id: "post", revision: "post-r1", contentRef: "content:post" },
],
edges: [],
}),
rootIds: ["post"],
concurrency: 1,
maximumBytes: 4,
load: async () => ({
format: "json",
revision: "post-r1",
source: '{"title":"Hello"}',
}),
})
).rejects.toMatchObject({
code: "DOCUMENT_LOAD_FAILED",
documentId: "post",
cause: expect.objectContaining({ code: "CONTENT_LIMIT_EXCEEDED" }),
});
});
test("rejects a loaded revision before parsing stale document bytes", async () => {
await expect(
resolveAdaptedDocumentGraph({
graph: createDocumentGraph({
nodes: [
{ id: "post", revision: "post-r1", contentRef: "content:post" },
],
edges: [],
}),
rootIds: ["post"],
concurrency: 1,
load: async () => ({
format: "json",
revision: "stale-r1",
source: "not valid JSON",
}),
})
).rejects.toMatchObject({
code: "DOCUMENT_LOAD_FAILED",
documentId: "post",
cause: expect.objectContaining({
code: "REVISION_MISMATCH",
expectedRevision: "post-r1",
actualRevision: "stale-r1",
}),
});
});
test("limits the reachable document count before loading", async () => {
const load = async () => ({
format: "json" as const,
revision: "unused",
source: "{}",
});
await expect(
resolveAdaptedDocumentGraph({
graph,
rootIds: ["post"],
concurrency: 3,
maximumDocuments: 2,
load,
})
).rejects.toMatchObject({
code: "DOCUMENT_COUNT_EXCEEDED",
documentCount: 3,
documentLimit: 2,
});
});
test("limits aggregate source bytes before parsing", async () => {
await expect(
resolveAdaptedDocumentGraph({
graph: createDocumentGraph({
nodes: [
{ id: "post", revision: "post-r1", contentRef: "content:post" },
],
edges: [],
}),
rootIds: ["post"],
concurrency: 1,
maximumBytes: 10,
maximumTotalBytes: 2,
load: async () => ({
format: "json",
revision: "post-r1",
source: "{}\n",
}),
})
).rejects.toMatchObject({
code: "DOCUMENT_LOAD_FAILED",
documentId: "post",
cause: expect.objectContaining({
code: "TOTAL_BYTES_EXCEEDED",
totalBytes: 3,
totalByteLimit: 2,
}),
});
});
test("shares immutable document work while enforcing each resolution budget", async () => {
const singleDocumentGraph = createDocumentGraph({
nodes: [{ id: "post", revision: "post-r1", contentRef: "content:post" }],
edges: [],
});
const load = vi.fn(async () => ({
format: "json" as const,
revision: "post-r1",
source: "{}\n",
}));
const session = createDocumentResolutionSession({ load, concurrency: 1 });
const parse = vi.spyOn(JSON, "parse");
try {
await expect(
session.resolve({
graph: singleDocumentGraph,
rootIds: ["post"],
maximumTotalBytes: 3,
})
).resolves.toMatchObject({ roots: [{ format: "json", value: {} }] });
await expect(
session.resolve({
graph: singleDocumentGraph,
rootIds: ["post"],
maximumTotalBytes: 3,
})
).resolves.toMatchObject({ roots: [{ format: "json", value: {} }] });
await expect(
session.resolve({
graph: singleDocumentGraph,
rootIds: ["post"],
maximumTotalBytes: 2,
})
).rejects.toMatchObject({
code: "DOCUMENT_LOAD_FAILED",
cause: expect.objectContaining({
code: "TOTAL_BYTES_EXCEEDED",
totalBytes: 3,
totalByteLimit: 2,
}),
});
expect(
parse.mock.calls.filter(([source]) => source === "{}\n")
).toHaveLength(1);
} finally {
parse.mockRestore();
}
expect(load).toHaveBeenCalledOnce();
});
test("checks each resolution budget before parsing shared bytes", async () => {
const singleDocumentGraph = createDocumentGraph({
nodes: [{ id: "post", revision: "post-r1", contentRef: "content:post" }],
edges: [],
});
const load = vi.fn(async () => ({
format: "json" as const,
revision: "post-r1",
source: "not json",
}));
const session = createDocumentResolutionSession({ load, concurrency: 1 });
await expect(
session.resolve({
graph: singleDocumentGraph,
rootIds: ["post"],
maximumTotalBytes: 2,
})
).rejects.toMatchObject({
code: "DOCUMENT_LOAD_FAILED",
cause: expect.objectContaining({
code: "TOTAL_BYTES_EXCEEDED",
totalByteLimit: 2,
}),
});
expect(load).toHaveBeenCalledOnce();
});
test("reports the session byte limit for an oversized shared source", async () => {
const singleDocumentGraph = createDocumentGraph({
nodes: [{ id: "post", revision: "post-r1", contentRef: "content:post" }],
edges: [],
});
const session = createDocumentResolutionSession({
load: async () => ({
format: "json",
revision: "post-r1",
source: "123456",
}),
concurrency: 1,
maximumDocumentBytes: 4,
});
await expect(
session.resolve({
graph: singleDocumentGraph,
rootIds: ["post"],
})
).rejects.toMatchObject({
code: "DOCUMENT_LOAD_FAILED",
cause: expect.objectContaining({
code: "CONTENT_LIMIT_EXCEEDED",
contentByteLimit: 4,
}),
});
});
test("bounds source materialization across concurrent resolutions", async () => {
const independentGraph = createDocumentGraph({
nodes: ["a", "b", "c", "d"].map((id) => ({
id,
revision: `${id}-r1`,
contentRef: `content:${id}`,
})),
edges: [],
});
let activeLoads = 0;
let maximumActiveLoads = 0;
const load = vi.fn(
async (node: (typeof independentGraph.nodes)[number]) => {
activeLoads += 1;
maximumActiveLoads = Math.max(maximumActiveLoads, activeLoads);
await Promise.resolve();
activeLoads -= 1;
return {
format: "json" as const,
revision: node.revision,
source: "{}",
};
}
);
const session = createDocumentResolutionSession({ load, concurrency: 2 });
await Promise.all([
session.resolve({ graph: independentGraph, rootIds: ["a", "b"] }),
session.resolve({ graph: independentGraph, rootIds: ["c", "d"] }),
]);
expect(maximumActiveLoads).toBe(2);
});
test("keeps total-byte failures stable when one source is cached", async () => {
const independentGraph = createDocumentGraph({
nodes: ["a", "b"].map((id) => ({
id,
revision: `${id}-r1`,
contentRef: `content:${id}`,
})),
edges: [],
});
const warmSession = createDocumentResolutionSession({
load: async (node) => ({
format: "json",
revision: node.revision,
source: "{}",
}),
concurrency: 2,
});
await warmSession.resolve({ graph: independentGraph, rootIds: ["a"] });
const cachedFailure = warmSession.resolve({
graph: independentGraph,
rootIds: ["a", "b"],
maximumTotalBytes: 3,
});
const cachedExpectation = expect(cachedFailure).rejects.toMatchObject({
cause: expect.objectContaining({ documentId: "b" }),
});
let releaseA = () => {};
const waitForA = new Promise<void>((resolve) => {
releaseA = resolve;
});
const load = vi.fn(
async (node: (typeof independentGraph.nodes)[number]) => {
if (node.id === "a") {
await waitForA;
}
return {
format: "json" as const,
revision: node.revision,
source: "{}",
};
}
);
const freshSession = createDocumentResolutionSession({
load,
concurrency: 2,
});
const freshFailure = freshSession.resolve({
graph: independentGraph,
rootIds: ["a", "b"],
maximumTotalBytes: 3,
});
await vi.waitFor(() => expect(load).toHaveBeenCalledTimes(2));
releaseA();
await cachedExpectation;
await expect(freshFailure).rejects.toMatchObject({
cause: expect.objectContaining({ documentId: "b" }),
});
});
test("settles active, shared, and queued resolutions when cancelled", async () => {
const independentGraph = createDocumentGraph({
nodes: ["a", "b"].map((id) => ({
id,
revision: `${id}-r1`,
contentRef: `content:${id}`,
})),
edges: [],
});
const controller = new AbortController();
let releaseFirstLoad = () => {};
const firstLoad = new Promise<void>((resolve) => {
releaseFirstLoad = resolve;
});
const load = vi.fn(
async (node: (typeof independentGraph.nodes)[number]) => {
if (node.id === "a") {
await firstLoad;
}
return {
format: "json" as const,
revision: node.revision,
source: "{}",
};
}
);
const session = createDocumentResolutionSession({
load,
concurrency: 1,
signal: controller.signal,
});
const first = session.resolve({
graph: independentGraph,
rootIds: ["a"],
});
await vi.waitFor(() => expect(load).toHaveBeenCalledOnce());
const pending = [
first,
session.resolve({ graph: independentGraph, rootIds: ["a"] }),
session.resolve({ graph: independentGraph, rootIds: ["b"] }),
];
const results: Array<PromiseSettledResult<unknown> | undefined> =
Array.from({ length: pending.length });
const tracked = pending.map((promise, index) =>
promise.then(
(value) => {
results[index] = { status: "fulfilled", value };
},
(reason) => {
results[index] = { status: "rejected", reason };
}
)
);
controller.abort("test cancellation");
try {
await vi.waitFor(() =>
expect(results).toMatchObject(
Array.from({ length: pending.length }, () => ({
status: "rejected",
reason: { code: "REQUEST_CANCELLED" },
}))
)
);
} finally {
releaseFirstLoad();
}
await Promise.all(tracked);
expect(load).toHaveBeenCalledOnce();
});
});