diff --git a/packages/sdk/src/authored-flow-loader.ts b/packages/sdk/src/authored-flow-loader.ts index 10ceaf8a4..236e86adc 100644 --- a/packages/sdk/src/authored-flow-loader.ts +++ b/packages/sdk/src/authored-flow-loader.ts @@ -311,14 +311,54 @@ 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` 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 reads: Array> = []; + let failed = false, next = 0; + const start = (): void => { + const read = readFile(paths[next++]!); + read.catch(() => { failed = true; }); + reads.push(read); + }; + 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 // 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..2290d0773 --- /dev/null +++ b/packages/sdk/tests/authored-surface-hash.test.ts @@ -0,0 +1,132 @@ +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, 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[] = []; + 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; + maxInFlight = Math.max(maxInFlight, inFlight); + try { + await new Promise(resolve => setTimeout(resolve, delayMs(path))); + const error = fail(path); + if (error !== undefined) { + startedAtFirstFailure ??= started.length; + throw error; + } + return await realReadFile(path); + } finally { + inFlight -= 1; + startedWhenSettled.set(path, started.length); + settledAt.set(path, performance.now()); + } + }) as typeof fsPromises.readFile); + return { started, startedWhenSettled, settledAt, maxInFlight: () => maxInFlight, + startedAtFirstFailure: () => startedAtFirstFailure }; +} + +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('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[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 : path === files[10] ? 120 : 0), + path => (path === files[3] || path === files[5] ? new Error(`unreadable ${relative(root, path)}`) : undefined), + ); + 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); + }); +});