Skip to content
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

Break up request graph cache serialisation and run after build completion #9384

Merged
merged 24 commits into from
Feb 16, 2024
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
c3fd8f2
Break up request graph cache serialisation and run after build comple…
JakeLane Nov 15, 2023
c06fa33
Fix test to abort before writing to cache
JakeLane Nov 15, 2023
863b5bd
Write cache to disk when build fails
JakeLane Nov 16, 2023
d93e422
Move cache aborting to build queue
JakeLane Nov 16, 2023
63f0017
Fix cache node shallow copy
JakeLane Nov 17, 2023
0cfdedb
Merge branch 'v2' into jlane2/write-request-graph-to-disk-background
JakeLane Nov 28, 2023
d1e726d
Merge branch 'v2' of github.com:parcel-bundler/parcel into jlane2/wri…
JakeLane Dec 8, 2023
b82ab4c
Resolve windows cache path issue
JakeLane Dec 12, 2023
07302ca
Merge branch 'v2' into jlane2/write-request-graph-to-disk-background
JakeLane Dec 12, 2023
80507da
Simplify cache chunking by moving implementation to FSCache
JakeLane Dec 13, 2023
730c274
Use promise queue to manage cache writes
JakeLane Dec 13, 2023
e5d8565
Merge branch 'v2' into jlane2/write-request-graph-to-disk-background
JakeLane Dec 14, 2023
51ffd03
Resolve unhandled errors with promise queue
JakeLane Dec 14, 2023
84d0e1d
Only serialise and write cache chunks to disk when changed
JakeLane Jan 25, 2024
ed110a1
Merge branch 'v2' of github.com:parcel-bundler/parcel into jlane2/wri…
JakeLane Jan 25, 2024
48f1d25
Merge branch 'v2' into jlane2/write-request-graph-to-disk-background
JakeLane Feb 6, 2024
96c1abc
Add getRequestGraphNodeKey function and refactor for loop
JakeLane Feb 8, 2024
c88cab5
Move to set to track cached requests to disk
JakeLane Feb 8, 2024
921c7ba
Bring back catch on queue add
JakeLane Feb 8, 2024
6d339a6
Update unit test for RequestTracker
JakeLane Feb 9, 2024
3965abb
Update progress for cache write and handle node invalidation
JakeLane Feb 15, 2024
e0b3ba2
Update unit test to use new graph set
JakeLane Feb 15, 2024
3d8b1e3
Invalidate written cache on disk on request completion
JakeLane Feb 15, 2024
0941434
Merge branch 'v2' into jlane2/write-request-graph-to-disk-background
JakeLane Feb 16, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
39 changes: 24 additions & 15 deletions packages/core/cache/src/FSCache.js
Original file line number Diff line number Diff line change
Expand Up @@ -105,25 +105,34 @@ export class FSCache implements Cache {
async setLargeBlob(key: string, contents: Buffer | string): Promise<void> {
const chunks = Math.ceil(contents.length / WRITE_LIMIT_CHUNK);

const writePromises: Promise<void>[] = [];
if (chunks === 1) {
// If there's one chunk, don't slice the content
await this.fs.writeFile(this.#getFilePath(key, 0), contents);
return;
}

const writePromises: Promise<void>[] = [];
for (let i = 0; i < chunks; i += 1) {
writePromises.push(
this.fs.writeFile(
this.#getFilePath(key, i),
typeof contents === 'string'
? contents.slice(i * WRITE_LIMIT_CHUNK, (i + 1) * WRITE_LIMIT_CHUNK)
: contents.subarray(
i * WRITE_LIMIT_CHUNK,
(i + 1) * WRITE_LIMIT_CHUNK,
),
),
this.fs.writeFile(this.#getFilePath(key, 0), contents),
);
} else {
for (let i = 0; i < chunks; i += 1) {
writePromises.push(
this.fs.writeFile(
this.#getFilePath(key, i),
typeof contents === 'string'
? contents.slice(
i * WRITE_LIMIT_CHUNK,
(i + 1) * WRITE_LIMIT_CHUNK,
)
: contents.subarray(
i * WRITE_LIMIT_CHUNK,
(i + 1) * WRITE_LIMIT_CHUNK,
),
),
);
}
}

// If there's already a file following this chunk, it's old and should be removed
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does it matter if it had extra chunks after that, or does that just become "garbage"?

i.e. if you had chunks 0, 1, 2, 3 (unlikely given the sizes - but still..), and next time have 0,1, you'll delete 2 but leave 3 dangling?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah I left it dangling as the intention was purely to cut the edge case of joining two different chunks together. In retrospect, it's not complex to just delete everything so I'll add that

if (await this.fs.exists(this.#getFilePath(key, chunks))) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that async existence checking is long deprecated in Node, and can lead to race conditions: https://nodejs.org/api/fs.html#fsexistspath-callback (i.e. the recommended approach would be to just try and unlink and ignore failure)

writePromises.push(this.fs.unlink(this.#getFilePath(key, chunks)));
}

await Promise.all(writePromises);
Expand Down
49 changes: 35 additions & 14 deletions packages/core/cache/src/LMDBCache.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type {FilePath} from '@parcel/types';
import type {Cache} from './types';
import type {Readable, Writable} from 'stream';

import type {AbortSignal} from 'abortcontroller-polyfill/dist/cjs-ponyfill';
import stream from 'stream';
import path from 'path';
import {promisify} from 'util';
Expand Down Expand Up @@ -111,27 +112,47 @@ export class LMDBCache implements Cache {
return Buffer.concat(await Promise.all(buffers));
}

async setLargeBlob(key: string, contents: Buffer | string): Promise<void> {
async setLargeBlob(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there any elegant way to share the implementation between the two Cache types as (AFAICT) they're identical?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instantiate a FSCache instance inside lmdb cache and forward calls of setLargeBlob to that?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That sounds good to me, will clean this up

key: string,
contents: Buffer | string,
options?: {|signal?: AbortSignal|},
): Promise<void> {
const chunks = Math.ceil(contents.length / WRITE_LIMIT_CHUNK);

const writePromises: Promise<void>[] = [];
if (chunks === 1) {
// If there's one chunk, don't slice the content
await this.fs.writeFile(this.#getFilePath(key, 0), contents);
return;
writePromises.push(
this.fs.writeFile(this.#getFilePath(key, 0), contents, {
signal: options?.signal,
}),
);
} else {
for (let i = 0; i < chunks; i += 1) {
writePromises.push(
this.fs.writeFile(
this.#getFilePath(key, i),
typeof contents === 'string'
? contents.slice(
i * WRITE_LIMIT_CHUNK,
(i + 1) * WRITE_LIMIT_CHUNK,
)
: contents.subarray(
i * WRITE_LIMIT_CHUNK,
(i + 1) * WRITE_LIMIT_CHUNK,
),
{signal: options?.signal},
),
);
}
}

const writePromises: Promise<void>[] = [];
for (let i = 0; i < chunks; i += 1) {
// If there's already a file following this chunk, it's old and should be removed
if (await this.fs.exists(this.#getFilePath(key, chunks))) {
writePromises.push(
this.fs.writeFile(
this.#getFilePath(key, i),
typeof contents === 'string'
? contents.slice(i * WRITE_LIMIT_CHUNK, (i + 1) * WRITE_LIMIT_CHUNK)
: contents.subarray(
i * WRITE_LIMIT_CHUNK,
(i + 1) * WRITE_LIMIT_CHUNK,
),
),
this.fs.unlink(this.#getFilePath(key, chunks), {
signal: options?.signal,
}),
);
}

Expand Down
7 changes: 6 additions & 1 deletion packages/core/cache/src/types.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// @flow
import type {Readable} from 'stream';
import type {AbortSignal} from 'abortcontroller-polyfill/dist/cjs-ponyfill';

export interface Cache {
ensure(): Promise<void>;
Expand All @@ -12,7 +13,11 @@ export interface Cache {
setBlob(key: string, contents: Buffer | string): Promise<void>;
hasLargeBlob(key: string): Promise<boolean>;
getLargeBlob(key: string): Promise<Buffer>;
setLargeBlob(key: string, contents: Buffer | string): Promise<void>;
setLargeBlob(
key: string,
contents: Buffer | string,
options?: {|signal?: AbortSignal|},
): Promise<void>;
getBuffer(key: string): Promise<?Buffer>;
/**
* In a multi-threaded environment, where there are potentially multiple Cache
Expand Down
29 changes: 27 additions & 2 deletions packages/core/core/src/Parcel.js
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,8 @@ export default class Parcel {
}

let result = await this._build({startTime});

await this.#requestTracker.writeToCache();
await this._end();

if (result.type === 'buildFailure') {
Expand All @@ -175,10 +177,31 @@ export default class Parcel {
async _end(): Promise<void> {
this.#initialized = false;

await this.#requestTracker.writeToCache();
await this.#disposable.dispose();
}

async writeRequestTrackerToCache(): Promise<void> {
if (this.#watchQueue.getNumWaiting() === 0) {
// If there's no queued events, we are safe to write the request graph to disk
const abortController = new AbortController();

const unsubscribe = this.#watchQueue.subscribeToAdd(() => {
abortController.abort();
});

try {
await this.#requestTracker.writeToCache(abortController.signal);
} catch (err) {
if (!abortController.signal.aborted) {
// We expect abort errors if we interrupt the cache write
throw err;
}
}

unsubscribe();
}
}

async _startNextBuild(): Promise<?BuildEvent> {
this.#watchAbortController = new AbortController();
await this.#farm.callAllWorkers('clearConfigCache', []);
Expand All @@ -198,6 +221,9 @@ export default class Parcel {
if (!(err instanceof BuildAbortError)) {
throw err;
}
} finally {
// If the build passes or fails, we want to cache the request graph
await this.writeRequestTrackerToCache();
}
}

Expand Down Expand Up @@ -372,7 +398,6 @@ export default class Parcel {
};

await this.#reporterRunner.report(event);

return event;
} finally {
if (this.isProfiling) {
Expand Down
144 changes: 98 additions & 46 deletions packages/core/core/src/RequestTracker.js
Original file line number Diff line number Diff line change
Expand Up @@ -846,6 +846,8 @@ export class RequestGraph extends ContentGraph<
}
}

const NODES_PER_BLOB = 2 ** 14;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How did we arrive at this number?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I profiled locally on my machine on how long it took to serialise n nodes. I tuned n with binary search until I reached approximately ~50 ms serialisation time per blob. The goal is to free up the event loop for a reasonable amount of time for user perception.

I'll document this on the constant so it can be tuned in the future if required.


export default class RequestTracker {
graph: RequestGraph;
farm: WorkerFarm;
Expand Down Expand Up @@ -1108,55 +1110,88 @@ export default class RequestTracker {
return {api, subRequestContentKeys};
}

async writeToCache() {
let cacheKey = getCacheKey(this.options);
let requestGraphKey = hashString(`${cacheKey}:requestGraph`);
let snapshotKey = hashString(`${cacheKey}:snapshot`);
async writeToCache(signal?: AbortSignal) {
const cacheKey = getCacheKey(this.options);
const requestGraphKey = `requestGraph-${hashString(cacheKey)}`;
const snapshotKey = `snapshot-${hashString(cacheKey)}`;

if (this.options.shouldDisableCache) {
return;
}
let total = 2;

const serialisedGraph = this.graph.serialize();

let total = 0;
const serialiseAndSet = async (
key: string,
// $FlowFixMe serialise input is any type
contents: any,
): Promise<void> => {
if (signal?.aborted) {
throw new Error('Serialization was aborted');
}

await this.options.cache.setLargeBlob(
key,
serialize(contents),
signal
? {
signal: signal,
}
: undefined,
);

total += 1;

report({
type: 'cache',
phase: 'write',
total,
size: this.graph.nodes.length,
});
};

const promises: Promise<void>[] = [];

report({
type: 'cache',
phase: 'start',
total,
size: this.graph.nodes.length,
});
let promises = [];
for (let node of this.graph.nodes) {
if (!node || node.type !== REQUEST) {
continue;
}

let resultCacheKey = node.resultCacheKey;
if (resultCacheKey != null && node.result != null) {
promises.push(
this.options.cache.setLargeBlob(
resultCacheKey,
serialize(node.result),
),
);
total++;
report({
type: 'cache',
phase: 'write',
total,
size: this.graph.nodes.length,
});
delete node.result;
// Preallocating a sparse array is faster than pushing when N is high enough
const cacheableNodes = new Array(serialisedGraph.nodes.length);
for (let i = 0; i < serialisedGraph.nodes.length; i += 1) {
const node = serialisedGraph.nodes[i];

let resultCacheKey = node?.resultCacheKey;
if (
node?.type === REQUEST &&
resultCacheKey != null &&
node?.result != null
) {
promises.push(serialiseAndSet(resultCacheKey, node.result));
// eslint-disable-next-line no-unused-vars
const {result: _, ...newNode} = node;
cacheableNodes[i] = newNode;
} else {
cacheableNodes[i] = node;
}
}

for (let i = 0; i * NODES_PER_BLOB < cacheableNodes.length; i += 1) {
promises.push(
serialiseAndSet(
`requestGraph-nodes-${i}-${hashString(cacheKey)}`,
cacheableNodes.slice(i * NODES_PER_BLOB, (i + 1) * NODES_PER_BLOB),
),
);
}

promises.push(
this.options.cache.setLargeBlob(requestGraphKey, serialize(this.graph)),
serialiseAndSet(requestGraphKey, {...serialisedGraph, nodes: undefined}),
);
report({
type: 'cache',
phase: 'write',
total,
size: this.graph.nodes.length,
});

let opts = getWatcherOptions(this.options);
let snapshotPath = path.join(this.options.cacheDir, snapshotKey + '.txt');
Expand All @@ -1167,15 +1202,10 @@ export default class RequestTracker {
opts,
),
);
report({
type: 'cache',
phase: 'write',
total,
size: this.graph.nodes.length,
});
report({type: 'cache', phase: 'end', total, size: this.graph.nodes.length});

await Promise.all(promises);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How many concurrent promises will be typical here for a Jira cache? Promise.all with a large set, especially when writing files or doing other async IO stuff, can have sub-optimal performance. If the concurrency is large enough, you might have better results using async/queue with a concurrency limit set.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(We also have PromiseQueue in the utils for exactly this use case you haven't seen it in the codebase yet.)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(We also have PromiseQueue in the utils for exactly this use case you haven't seen it in the codebase yet.)

Ah, yeah, it's even touched in this PR 😅

I was thinking of Jira where I have used async/queue in the past for this..


report({type: 'cache', phase: 'end', total, size: this.graph.nodes.length});
}

static async init({
Expand Down Expand Up @@ -1205,20 +1235,42 @@ async function loadRequestGraph(options): Async<RequestGraph> {
return new RequestGraph();
}

let cacheKey = getCacheKey(options);
let requestGraphKey = hashString(`${cacheKey}:requestGraph`);
const cacheKey = getCacheKey(options);
const hashedCacheKey = hashString(cacheKey);
const requestGraphKey = `requestGraph-${hashedCacheKey}`;
if (await options.cache.hasLargeBlob(requestGraphKey)) {
let requestGraph: RequestGraph = deserialize(
await options.cache.getLargeBlob(requestGraphKey),
);
const getAndDeserialize = async (key: string) => {
return deserialize(await options.cache.getLargeBlob(key));
};

let i = 0;
let nodePromises = [];
while (
await options.cache.hasLargeBlob(
`requestGraph-nodes-${i}-${hashedCacheKey}`,
)
) {
nodePromises.push(
getAndDeserialize(`requestGraph-nodes-${i}-${hashedCacheKey}`),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We generate this string at least 3 different times. Could move it to a function so it's clear they're tied together?

);
i += 1;
}

const serializedRequestGraph = await getAndDeserialize(requestGraphKey);
const requestGraph = RequestGraph.deserialize({
...serializedRequestGraph,
nodes: (await Promise.all(nodePromises)).flatMap(nodeChunk => nodeChunk),
});

let opts = getWatcherOptions(options);
let snapshotKey = hashString(`${cacheKey}:snapshot`);
let snapshotKey = `snapshot-${hashedCacheKey}`;
let snapshotPath = path.join(options.cacheDir, snapshotKey + '.txt');
let events = await options.inputFS.getEventsSince(
options.projectRoot,
snapshotPath,
opts,
);

requestGraph.invalidateUnpredictableNodes();
requestGraph.invalidateOnBuildNodes();
requestGraph.invalidateEnvNodes(options.env);
Expand Down