From 999be9c6626ef24d2139682847669e40494a1ac4 Mon Sep 17 00:00:00 2001 From: Miya Date: Mon, 26 Oct 2026 01:26:46 +0100 Subject: [PATCH 1/2] perf(sdk): hash the Surface package with concurrent reads, same digest The CLI hashes the installed @relayflows/surface tree while loading an authored flow, and the authored Node child hashes it again while loading the pinned source. Both awaited one readFile at a time over ~600 files. Read with up to 32 reads in flight and feed each file to the hash strictly in the sorted walk order, so the digest is byte-identical. After a failure no new read starts, and the lowest-index failure is thrown, which is the error the serial walk meets first. Co-Authored-By: Claude Opus 5.5 --- packages/sdk/src/authored-flow-loader.ts | 41 ++++++- .../sdk/tests/authored-surface-hash.test.ts | 108 ++++++++++++++++++ 2 files changed, 146 insertions(+), 3 deletions(-) create mode 100644 packages/sdk/tests/authored-surface-hash.test.ts diff --git a/packages/sdk/src/authored-flow-loader.ts b/packages/sdk/src/authored-flow-loader.ts index 10ceaf8a4..3171b865c 100644 --- a/packages/sdk/src/authored-flow-loader.ts +++ b/packages/sdk/src/authored-flow-loader.ts @@ -311,14 +311,49 @@ export async function packageTreeSha256(root: string): Promise { } await visit(root); const hash = createHash('sha256'); - for (const path of files) { - const bytes = await readFile(path); + await readInOrder(files, SURFACE_READ_CONCURRENCY, (path, bytes) => { const name = relative(root, path).split(sep).join('/'); hash.update(name).update('\0').update(String(bytes.length)).update('\0').update(bytes); - } + }); return hash.digest('hex'); } +/** + * Surface is about 600 small files, and both the CLI and the authored Node + * child hash it on the startup path. Awaiting one read at a time paid a + * filesystem round trip per file; a sandbox disk made that several hundred ms. + */ +const SURFACE_READ_CONCURRENCY = 32; + +/** + * Read `paths` with at most `limit` reads in flight, but hand each file to + * `consume` strictly in `paths` order, so the digest is the serial walk's. + * After a failure no new read starts; once the started reads settle, the + * lowest-index failure is thrown, which is the error a serial walk would hit. + */ +async function readInOrder( + paths: readonly string[], + limit: number, + consume: (path: string, bytes: Buffer) => void, +): Promise { + const ready = new Map(); + const failures = new Map(); + let next = 0, consumed = 0; + const worker = async (): Promise => { + while (failures.size === 0 && next < paths.length) { + const index = next++; + try { ready.set(index, await readFile(paths[index]!)); } catch (error) { failures.set(index, error); } + for (let bytes = ready.get(consumed); bytes !== undefined; bytes = ready.get(consumed)) { + ready.delete(consumed); + consume(paths[consumed]!, bytes); + consumed += 1; + } + } + }; + await Promise.all(Array.from({ length: Math.min(limit, paths.length) }, worker)); + if (failures.size !== 0) throw failures.get(Math.min(...failures.keys())); +} + // Exported for callers (internal SDK tests, and any co-located flow that is // provably the same `@relayflows/surface` instance as this package) that // have no need to resolve a separate copy. diff --git a/packages/sdk/tests/authored-surface-hash.test.ts b/packages/sdk/tests/authored-surface-hash.test.ts new file mode 100644 index 000000000..b7111e3fc --- /dev/null +++ b/packages/sdk/tests/authored-surface-hash.test.ts @@ -0,0 +1,108 @@ +import * as fsPromises from 'node:fs/promises'; +import { createHash } from 'node:crypto'; +import { createRequire } from 'node:module'; +import { tmpdir } from 'node:os'; +import { dirname, join, relative, sep } from 'node:path'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { packageTreeSha256 } from '../src/authored-flow-loader.js'; + +// The source imports readFile by name; mocking the module makes it spy-able. +vi.mock('node:fs/promises', async (importOriginal) => ({ + ...await importOriginal(), +})); + +const realReadFile = (await vi.importActual('node:fs/promises')).readFile; +const directories: string[] = []; + +afterEach(async () => { + vi.restoreAllMocks(); + for (const directory of directories.splice(0)) { + await fsPromises.rm(directory, { recursive: true, force: true }); + } +}); + +/** The serial walk this hash has always been: sorted entries, one awaited read per file. */ +async function serialTreeSha256(root: string): Promise { + const files: string[] = []; + async function visit(directory: string): Promise { + const entries = await fsPromises.readdir(directory, { withFileTypes: true }); + entries.sort((a, b) => a.name.localeCompare(b.name)); + for (const entry of entries) { + if (directory === root && entry.name === 'node_modules') continue; + const path = join(directory, entry.name); + if (entry.isDirectory()) await visit(path); + else files.push(path); + } + } + await visit(root); + const hash = createHash('sha256'); + for (const path of files) { + const bytes = await realReadFile(path); + hash.update(relative(root, path).split(sep).join('/')).update('\0').update(String(bytes.length)).update('\0').update(bytes); + } + return hash.digest('hex'); +} + +/** + * 80 files over nested directories, created in the walk's sorted order, sized + * so concurrent reads finish out of order. + */ +async function payloadTree(): Promise<{ root: string; files: string[] }> { + const root = await fsPromises.mkdtemp(join(tmpdir(), 'surface-hash-')); + directories.push(root); + const files: string[] = []; + for (let index = 0; index < 80; index += 1) { + const path = join(root, 'dist', `group-${Math.floor(index / 20)}`, `file-${String(index).padStart(2, '0')}.js`); + await fsPromises.mkdir(dirname(path), { recursive: true }); + await fsPromises.writeFile(path, `export const value${index} = ${JSON.stringify('x'.repeat((index * 7919) % 20_000))};\n`); + files.push(path); + } + await fsPromises.writeFile(join(root, 'package.json'), '{"name":"@relayflows/surface","version":"2.0.10"}'); + return { root, files }; +} + +/** Count and delay every readFile, optionally failing chosen paths. */ +function delayedReads(delayMs: (path: string) => number, fail: (path: string) => Error | undefined = () => undefined) { + const started: string[] = []; + let inFlight = 0, maxInFlight = 0; + vi.spyOn(fsPromises, 'readFile').mockImplementation((async (path: string) => { + started.push(path); + inFlight += 1; + maxInFlight = Math.max(maxInFlight, inFlight); + try { + await new Promise(resolve => setTimeout(resolve, delayMs(path))); + const error = fail(path); + if (error !== undefined) throw error; + return await realReadFile(path); + } finally { inFlight -= 1; } + }) as typeof fsPromises.readFile); + return { started, maxInFlight: () => maxInFlight }; +} + +describe('Surface package tree hash', () => { + it('hashes the installed @relayflows/surface exactly as the serial walk does', async () => { + const require = createRequire(import.meta.url); + let root = dirname(require.resolve('@relayflows/surface/runtime')); + while (!(await fsPromises.readdir(root)).includes('package.json')) root = dirname(root); + expect(await packageTreeSha256(root)).toBe(await serialTreeSha256(root)); + }); + + it('reads files concurrently and still hashes them in path order', async () => { + const { root, files } = await payloadTree(); + const reads = delayedReads(path => (files.length - files.indexOf(path)) % 9); + expect(await packageTreeSha256(root)).toBe(await serialTreeSha256(root)); + expect(reads.maxInFlight()).toBeGreaterThan(1); + expect(reads.maxInFlight()).toBeLessThanOrEqual(32); + }); + + it('starts no new read after a failure and throws the error the serial walk meets first', async () => { + const { root, files } = await payloadTree(); + // files[3] fails late, files[5] fails at once: the serial walk meets files[3] first. + const reads = delayedReads( + path => (path === files[3] ? 40 : 0), + path => (path === files[3] || path === files[5] ? new Error(`unreadable ${relative(root, path)}`) : undefined), + ); + await expect(packageTreeSha256(root)).rejects.toThrow(`unreadable ${relative(root, files[3]!)}`); + expect(reads.started.length).toBeLessThan(files.length); + }); +}); From e5053b2bfb4aa74b2e104110fd8a1ba7b98c122d Mon Sep 17 00:00:00 2001 From: Miya Date: Mon, 26 Oct 2026 02:00:03 +0100 Subject: [PATCH 2/2] perf(sdk): bound the Surface hash read-ahead by a window, not just reads in flight Review (#683): 32 workers bounded reads in flight but not the buffers waiting for an earlier, slow file, so the whole package could pile up in memory. Read through an in-order window of 32 files instead: a slow file stops new reads. After any failure no read starts, every started read settles, and the lowest-index failure is thrown, as before. Tests now pin the read-ahead bound, that no read starts after the first failure, and that the rejection waits for a read still in flight. Co-Authored-By: Claude Opus 5.5 --- packages/sdk/src/authored-flow-loader.ts | 43 +++++++++++-------- .../sdk/tests/authored-surface-hash.test.ts | 42 ++++++++++++++---- 2 files changed, 57 insertions(+), 28 deletions(-) diff --git a/packages/sdk/src/authored-flow-loader.ts b/packages/sdk/src/authored-flow-loader.ts index 3171b865c..236e86adc 100644 --- a/packages/sdk/src/authored-flow-loader.ts +++ b/packages/sdk/src/authored-flow-loader.ts @@ -326,32 +326,37 @@ export async function packageTreeSha256(root: string): Promise { const SURFACE_READ_CONCURRENCY = 32; /** - * Read `paths` with at most `limit` reads in flight, but hand each file to - * `consume` strictly in `paths` order, so the digest is the serial walk's. - * After a failure no new read starts; once the started reads settle, the - * lowest-index failure is thrown, which is the error a serial walk would hit. + * Read `paths` through a window of at most `limit` files, started in order + * and handed to `consume` strictly in `paths` order, so the digest is the + * serial walk's. The window bounds buffered bytes as well as reads in flight: + * a slow early file stops new reads instead of letting later files pile up. + * After any read fails no new read starts. The lowest-index failure, the + * error a serial walk would meet first, is thrown once every started read + * has settled. */ async function readInOrder( paths: readonly string[], limit: number, consume: (path: string, bytes: Buffer) => void, ): Promise { - const ready = new Map(); - const failures = new Map(); - let next = 0, consumed = 0; - const worker = async (): Promise => { - while (failures.size === 0 && next < paths.length) { - const index = next++; - try { ready.set(index, await readFile(paths[index]!)); } catch (error) { failures.set(index, error); } - for (let bytes = ready.get(consumed); bytes !== undefined; bytes = ready.get(consumed)) { - ready.delete(consumed); - consume(paths[consumed]!, bytes); - consumed += 1; - } - } + const reads: Array> = []; + let failed = false, next = 0; + const start = (): void => { + const read = readFile(paths[next++]!); + read.catch(() => { failed = true; }); + reads.push(read); }; - await Promise.all(Array.from({ length: Math.min(limit, paths.length) }, worker)); - if (failures.size !== 0) throw failures.get(Math.min(...failures.keys())); + while (next < paths.length && reads.length < limit) start(); + for (let index = 0; reads.length !== 0; index += 1) { + let bytes: Buffer; + try { bytes = await reads[0]!; } catch (error) { + await Promise.allSettled(reads); + throw error; + } + reads.shift(); + consume(paths[index]!, bytes); + if (!failed && next < paths.length) start(); + } } // Exported for callers (internal SDK tests, and any co-located flow that is diff --git a/packages/sdk/tests/authored-surface-hash.test.ts b/packages/sdk/tests/authored-surface-hash.test.ts index b7111e3fc..2290d0773 100644 --- a/packages/sdk/tests/authored-surface-hash.test.ts +++ b/packages/sdk/tests/authored-surface-hash.test.ts @@ -61,10 +61,12 @@ async function payloadTree(): Promise<{ root: string; files: string[] }> { return { root, files }; } -/** Count and delay every readFile, optionally failing chosen paths. */ +/** Count, delay and optionally fail every readFile, recording what started and when each settled. */ function delayedReads(delayMs: (path: string) => number, fail: (path: string) => Error | undefined = () => undefined) { const started: string[] = []; - let inFlight = 0, maxInFlight = 0; + const startedWhenSettled = new Map(); + const settledAt = new Map(); + let inFlight = 0, maxInFlight = 0, startedAtFirstFailure: number | undefined; vi.spyOn(fsPromises, 'readFile').mockImplementation((async (path: string) => { started.push(path); inFlight += 1; @@ -72,11 +74,19 @@ function delayedReads(delayMs: (path: string) => number, fail: (path: string) => try { await new Promise(resolve => setTimeout(resolve, delayMs(path))); const error = fail(path); - if (error !== undefined) throw error; + if (error !== undefined) { + startedAtFirstFailure ??= started.length; + throw error; + } return await realReadFile(path); - } finally { inFlight -= 1; } + } finally { + inFlight -= 1; + startedWhenSettled.set(path, started.length); + settledAt.set(path, performance.now()); + } }) as typeof fsPromises.readFile); - return { started, maxInFlight: () => maxInFlight }; + return { started, startedWhenSettled, settledAt, maxInFlight: () => maxInFlight, + startedAtFirstFailure: () => startedAtFirstFailure }; } describe('Surface package tree hash', () => { @@ -95,14 +105,28 @@ describe('Surface package tree hash', () => { expect(reads.maxInFlight()).toBeLessThanOrEqual(32); }); + it('reads ahead at most 32 files past one that is slow', async () => { + const { root, files } = await payloadTree(); + const reads = delayedReads(path => (path === files[0] ? 100 : 0)); + expect(await packageTreeSha256(root)).toBe(await serialTreeSha256(root)); + // Until the first file arrives nothing can be hashed, so later files must not pile up. + expect(reads.startedWhenSettled.get(files[0]!)).toBeLessThanOrEqual(32); + }); + it('starts no new read after a failure and throws the error the serial walk meets first', async () => { const { root, files } = await payloadTree(); - // files[3] fails late, files[5] fails at once: the serial walk meets files[3] first. + // files[5] fails at once and files[3] later, so the serial walk meets files[3] first. + // files[10] is still reading when files[3] fails; the rejection must wait for it. const reads = delayedReads( - path => (path === files[3] ? 40 : 0), + path => (path === files[3] ? 40 : path === files[10] ? 120 : 0), path => (path === files[3] || path === files[5] ? new Error(`unreadable ${relative(root, path)}`) : undefined), ); - await expect(packageTreeSha256(root)).rejects.toThrow(`unreadable ${relative(root, files[3]!)}`); - expect(reads.started.length).toBeLessThan(files.length); + let rejectedAt = 0; + await expect(packageTreeSha256(root).finally(() => { rejectedAt = performance.now(); })) + .rejects.toThrow(`unreadable ${relative(root, files[3]!)}`); + expect(reads.startedAtFirstFailure()).toBeDefined(); + expect(reads.started.length).toBe(reads.startedAtFirstFailure()); + expect(reads.started).toContain(files[10]); + expect(reads.settledAt.get(files[10]!) ?? Infinity, 'files[10] settled before the rejection').toBeLessThanOrEqual(rejectedAt); }); });