diff --git a/packages/sdk/src/cloud-run.ts b/packages/sdk/src/cloud-run.ts index bffd5e01f..94f628eb9 100644 --- a/packages/sdk/src/cloud-run.ts +++ b/packages/sdk/src/cloud-run.ts @@ -14,7 +14,7 @@ import { type CloudConnectionOptions, } from './cloud-http.js'; import { cloudRunState, isCloudRunActive, type CloudRunState } from './cloud-run-record.js'; -import { packWorkingTree, prepareCloudSync, uploadCloudCode } from './cloud-sync.js'; +import { canUseCodeCache, packWorkingTree, prepareCloudSync, sha256PackedTree, uploadCloudCode } from './cloud-sync.js'; export type CloudFlowSource = FlowSpec | { path: string }; export const MIN_CLOUD_RUN_BUDGET_MINUTES = 30; @@ -65,7 +65,7 @@ export interface CloudRunReceipt { specHash: string; /** Authenticated run API resource; this is not a public sharing URL. */ apiUrl: string; - /** Present when a working tree was synced: what was uploaded, by count and size. */ + /** Present when a working tree was synced: its file count and uncompressed size. */ synced?: { files: number; bytes: number; skippedLinks: string[] }; } export interface CloudAuthoredAuthority { @@ -300,25 +300,34 @@ export async function runInCloud( // under it, so the run request below names code Cloud already holds. A // refused backend or failed upload therefore never leaves a launched run // pointing at a tree that is not there. - let synced: { runId: string; codeKey: string; files: number; bytes: number; skippedLinks: string[] } | undefined; + let synced: { runId: string; codeKey: string; codeCacheHit: boolean; files: number; bytes: number; skippedLinks: string[] } | undefined; if (options.syncCode !== undefined) { - const prepared = await prepareCloudSync(options); options.signal?.throwIfAborted(); const packed = await packWorkingTree(options.syncCode.root); + let prepared: Awaited>; try { options.signal?.throwIfAborted(); - await uploadCloudCode(prepared, packed, options); + const digest = canUseCodeCache(packed) ? await sha256PackedTree(packed) : undefined; + prepared = await prepareCloudSync(options, digest); + options.signal?.throwIfAborted(); + if (!prepared.codeCacheHit) await uploadCloudCode(prepared, packed, options); } finally { packed.dispose(); } - synced = { runId: prepared.runId, codeKey: prepared.codeKey, files: packed.files.length, bytes: packed.bytes, + synced = { runId: prepared.runId, codeKey: prepared.codeKey, codeCacheHit: prepared.codeCacheHit === true, + files: packed.files.length, bytes: packed.bytes, skippedLinks: packed.skippedLinks }; } options.signal?.throwIfAborted(); options.onSubmit?.(); let result: unknown; try { - result = await cloudFetch('/api/v1/workflows/run', options, { method: 'POST', detail: true, body: JSON.stringify({ + // A cache hit is copied into the run prefix after admission. The R2 copy + // may outlast the normal 30s request budget; explicit caller limits win. + const submitOptions = synced?.codeCacheHit + ? { ...options, requestTimeoutMs: options.requestTimeoutMs ?? 300_000 } + : options; + result = await cloudFetch('/api/v1/workflows/run', submitOptions, { method: 'POST', detail: true, body: JSON.stringify({ ...cloudSubmissionBody(submission), ...(options.workspaceId === undefined ? {} : { workspaceId: options.workspaceId }), ...(options.runBudgetMinutes === undefined ? {} : { relayflowV2RunBudgetMinutes: options.runBudgetMinutes }), diff --git a/packages/sdk/src/cloud-sync.ts b/packages/sdk/src/cloud-sync.ts index 1781f54f3..f713dab4e 100644 --- a/packages/sdk/src/cloud-sync.ts +++ b/packages/sdk/src/cloud-sync.ts @@ -1,11 +1,12 @@ import { spawnSync } from 'node:child_process'; -import { createReadStream, createWriteStream, existsSync, lstatSync, mkdtempSync, readdirSync, readlinkSync, rmSync } from 'node:fs'; -import { readFile } from 'node:fs/promises'; +import { createReadStream, createWriteStream, existsSync, lstatSync, mkdtempSync, readdirSync, readlinkSync, rmSync, statSync } from 'node:fs'; +import { open, readFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'; import { Readable } from 'node:stream'; import { pipeline } from 'node:stream/promises'; import { createGzip } from 'node:zlib'; +import { createHash } from 'node:crypto'; import { CloudFlowError, cloudFetch, cloudRequest, cloudRunId, isCloudRecord, type CloudConnectionOptions, } from './cloud-http.js'; @@ -25,6 +26,8 @@ import { /** Uncompressed bytes. Matches the sandbox's extraction budget with headroom. */ export const MAX_SYNC_BYTES = 256 * 1024 * 1024; +/** Above this compressed size, use the unchanged legacy upload path. */ +export const MAX_CACHED_CODE_BYTES = 64 * 1024 * 1024; const ALWAYS_SKIPPED = new Set(['.git', 'node_modules']); const CODE_KEY = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u; @@ -33,11 +36,14 @@ export interface PreparedCloudSync { codeKey: string; /** Run-scoped upload credential from `prepare`; falls back to the session token. */ uploadToken?: string; + /** Cloud confirmed the immutable archive already exists in this workspace. */ + codeCacheHit?: boolean; } /** `POST /api/v1/workflows/prepare`, refusing every non-Cloud-API storage backend. */ -export async function prepareCloudSync(options: CloudConnectionOptions): Promise { - const receipt = await cloudFetch('/api/v1/workflows/prepare', options, { method: 'POST' }); +export async function prepareCloudSync(options: CloudConnectionOptions, codeSha256?: string): Promise { + const receipt = await cloudFetch('/api/v1/workflows/prepare', options, + { method: 'POST', ...(codeSha256 ? { body: JSON.stringify({ codeSha256 }) } : {}) }); if (!isCloudRecord(receipt)) throw new CloudFlowError('invalid_response', 'Cloud prepare returned a non-object.'); const storage = isCloudRecord(receipt.workflowStorage) ? receipt.workflowStorage : undefined; const credentials = isCloudRecord(receipt.s3Credentials) ? receipt.s3Credentials : undefined; @@ -49,6 +55,15 @@ export async function prepareCloudSync(options: CloudConnectionOptions): Promise } const codeKey = typeof receipt.s3CodeKey === 'string' ? receipt.s3CodeKey : ''; if (!CODE_KEY.test(codeKey)) throw new CloudFlowError('invalid_response', 'Cloud prepare returned an unusable code key.'); + const codeCache = isCloudRecord(receipt.codeCache) ? receipt.codeCache : undefined; + let codeCacheHit: boolean | undefined; + if (codeSha256 && (codeCache !== undefined || codeKey.startsWith('code-sha256-'))) { + if (!codeCache || codeCache.sha256 !== codeSha256 || typeof codeCache.hit !== 'boolean' + || codeKey !== `code-sha256-${codeSha256}.tar.gz`) { + throw new CloudFlowError('invalid_response', 'Cloud prepare returned an inconsistent code cache receipt.'); + } + codeCacheHit = codeCache.hit; + } const uploadToken = credentials?.cloudApiAccessToken; if (uploadToken !== undefined && typeof uploadToken !== 'string') { throw new CloudFlowError('invalid_response', 'Cloud prepare returned an unusable storage credential.'); @@ -56,9 +71,17 @@ export async function prepareCloudSync(options: CloudConnectionOptions): Promise return { runId: cloudRunId(receipt.runId), codeKey, ...(uploadToken === undefined ? {} : { uploadToken }), + ...(codeCacheHit === undefined ? {} : { codeCacheHit }), }; } +/** Hash the deterministic compressed archive without loading it into memory. */ +export async function sha256PackedTree(packed: PackedTree): Promise { + const hash = createHash('sha256'); + for await (const chunk of createReadStream(packed.archivePath)) hash.update(chunk); + return hash.digest('hex'); +} + export interface PackedTree { /** The gzip'd ustar, spooled to a temporary file; `dispose()` removes it. */ archivePath: string; @@ -125,6 +148,14 @@ export async function packWorkingTree(root: string): Promise { } try { await pipeline(Readable.from(flatten(entries())), createGzip({ level: 6 }), createWriteStream(archivePath)); + // zlib's OS byte can vary by platform while the tar contents are equal. + // 255 means unknown OS and does not affect decompression. + const archive = await open(archivePath, 'r+'); + try { + await archive.write(Buffer.from([255]), 0, 1, 9); + } finally { + await archive.close(); + } } catch (error) { dispose(); throw error; @@ -132,6 +163,10 @@ export async function packWorkingTree(root: string): Promise { return { archivePath, files: members, bytes, skippedLinks, dispose }; } +export function canUseCodeCache(packed: PackedTree): boolean { + return statSync(packed.archivePath).size <= MAX_CACHED_CODE_BYTES; +} + /** Yield file streams chunk by chunk so `Readable.from` never buffers a whole file. */ async function* flatten(source: AsyncGenerator): AsyncGenerator { for await (const part of source) { diff --git a/packages/sdk/tests/cloud-sync.test.ts b/packages/sdk/tests/cloud-sync.test.ts index 5627218be..13d4cdc50 100644 --- a/packages/sdk/tests/cloud-sync.test.ts +++ b/packages/sdk/tests/cloud-sync.test.ts @@ -1,5 +1,5 @@ import { execFileSync } from 'node:child_process'; -import { chmod, mkdir, mkdtemp, readFile, readdir, rm, stat, symlink, writeFile } from 'node:fs/promises'; +import { chmod, mkdir, mkdtemp, readFile, readdir, rm, stat, symlink, truncate, utimes, writeFile } from 'node:fs/promises'; import { execFile } from 'node:child_process'; import { promisify } from 'node:util'; import { tmpdir } from 'node:os'; @@ -9,8 +9,10 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import { runCli } from '../src/cli.js'; import { runInCloud } from '../src/cloud-run.js'; import { - CLOUD_SYNC_PATCH_EXCLUDES, applyCloudPatch, excludedPatchPaths, packWorkingTree, patchedPaths, + CLOUD_SYNC_PATCH_EXCLUDES, MAX_CACHED_CODE_BYTES, applyCloudPatch, canUseCodeCache, + excludedPatchPaths, packWorkingTree, patchedPaths, prepareCloudSync, + sha256PackedTree, } from '../src/cloud-sync.js'; const dirs: string[] = []; @@ -85,6 +87,48 @@ async function pack(root: string) { } describe('packWorkingTree', () => { + it('produces identical gzip bytes and digest for the same tree despite file mtime changes', async () => { + const root = await tempDir('cloud-sync-deterministic-'); + const path = join(root, 'content.txt'); + await writeFile(path, 'same bytes\n'); + await chmod(path, 0o644); + const first = await packWorkingTree(root); + const firstBytes = await readFile(first.archivePath); + const firstDigest = await sha256PackedTree(first); + first.dispose(); + await utimes(path, new Date('2020-01-01T00:00:00Z'), new Date('2026-10-16T00:00:00Z')); + await chmod(path, 0o600); // non-executable permission bits do not change the archive + const second = await packWorkingTree(root); + try { + expect(await readFile(second.archivePath)).toEqual(firstBytes); + expect(await sha256PackedTree(second)).toBe(firstDigest); + expect(firstBytes.subarray(4, 8)).toEqual(Buffer.alloc(4)); // gzip mtime + expect(firstBytes[9]).toBe(255); // normalized gzip OS byte + } finally { + second.dispose(); + } + await chmod(path, 0o755); // executable bits are retained intentionally + const third = await packWorkingTree(root); + try { + expect(await sha256PackedTree(third)).not.toBe(firstDigest); + } finally { + third.dispose(); + } + }); + + it('uses legacy upload when the compressed archive exceeds the cache buffer budget', async () => { + const root = await tempDir('cloud-sync-cache-cap-'); + await writeFile(join(root, 'a'), 'a'); + const packed = await packWorkingTree(root); + try { + expect(canUseCodeCache(packed)).toBe(true); + await truncate(packed.archivePath, MAX_CACHED_CODE_BYTES + 1); + expect(canUseCodeCache(packed)).toBe(false); + } finally { + packed.dispose(); + } + }); + it('packs a Git checkout by ls-files semantics: tracked plus untracked, never ignored, .git or node_modules', async () => { const root = await tempDir('cloud-sync-git-'); git(root, 'init', '-q'); @@ -231,6 +275,54 @@ describe('prepareCloudSync', () => { }); describe('runInCloud with syncCode', () => { + it('uploads once for identical trees and uploads again after a one-byte change', async () => { + const root = await tempDir('cloud-sync-cache-'); + await writeFile(join(root, 'flow.yaml'), JSON.stringify({ + version: '0.1.0', name: 'synced', steps: [{ id: 'ls', type: 'deterministic', command: 'ls' }], + })); + const dataPath = join(root, 'data.txt'); + await writeFile(dataPath, 'a'); + let prepares = 0; + let priorDigest = ''; + const { calls, options } = cloud({ + '/api/v1/workflows/prepare': ({ body }) => { + const digest = (body as { codeSha256: string }).codeSha256; + expect(digest).toMatch(/^[0-9a-f]{64}$/u); + prepares++; + const hit = digest === priorDigest; + priorDigest = digest; + return { ...PREPARED, runId: `run-${prepares}`, s3CodeKey: `code-sha256-${digest}.tar.gz`, + codeCache: { sha256: digest, hit } }; + }, + '/api/v1/workflows/runs/': () => ({ ok: true }), + '/api/v1/workflows/run': () => ({ runId: `run-${prepares}`, status: 'pending' }), + }); + await runInCloud({ path: join(root, 'flow.yaml') }, { ...options, syncCode: { root } }); + const deadline = vi.spyOn(AbortSignal, 'timeout'); + await runInCloud({ path: join(root, 'flow.yaml') }, { ...options, syncCode: { root } }); + expect(deadline.mock.calls.map(([milliseconds]) => milliseconds)).toEqual([30_000, 300_000]); + expect(calls.filter(call => call.method === 'PUT')).toHaveLength(1); + await writeFile(dataPath, 'b'); + await runInCloud({ path: join(root, 'flow.yaml') }, { ...options, syncCode: { root } }); + expect(calls.filter(call => call.method === 'PUT')).toHaveLength(2); + expect(new Set(calls.filter(call => call.method === 'PUT').map(call => call.path)).size).toBe(2); + }); + + it('refuses a prepare response whose digest differs from the packed tree', async () => { + const root = await tempDir('cloud-sync-wrong-digest-'); + await writeFile(join(root, 'flow.yaml'), JSON.stringify({ + version: '0.1.0', name: 'synced', steps: [{ id: 'ls', type: 'deterministic', command: 'ls' }], + })); + const wrong = 'a'.repeat(64); + const { calls, options } = cloud({ + '/api/v1/workflows/prepare': () => ({ ...PREPARED, + s3CodeKey: `code-sha256-${wrong}.tar.gz`, codeCache: { sha256: wrong, hit: true } }), + }); + await expect(runInCloud({ path: join(root, 'flow.yaml') }, { ...options, syncCode: { root } })) + .rejects.toMatchObject({ code: 'invalid_response' }); + expect(calls.filter(call => call.method === 'PUT')).toHaveLength(0); + }); + it('prepares, uploads through the Cloud API with the run-scoped token, then submits against the prepared run', async () => { const root = await tempDir('cloud-sync-run-'); await writeFile(join(root, 'flow.yaml'), JSON.stringify({