diff --git a/scripts/benchmark-research.ts b/scripts/benchmark-research.ts index 5c4f571f..1cefeadb 100644 --- a/scripts/benchmark-research.ts +++ b/scripts/benchmark-research.ts @@ -247,25 +247,57 @@ async function child(workload: Workload) { }; } -function command(args: string[]): string { - const result = Bun.spawnSync(args, { cwd: root, stdout: 'pipe', stderr: 'pipe' }); +function command(args: string[], cwd: string = root): string { + const result = Bun.spawnSync(args, { cwd, stdout: 'pipe', stderr: 'pipe' }); if (result.exitCode !== 0) { throw new Error(`${args[0]} failed: ${result.stderr.toString()}`); } return result.stdout.toString().trimEnd(); } -export function identity() { - const paths = command(['git', 'ls-files', '--cached', '--others', '--exclude-standard', '-z']) +function errorCode(error: unknown): string | undefined { + if (typeof error === 'object' && error !== null && 'code' in error) { + const code = (error as { code?: unknown }).code; + return typeof code === 'string' ? code : undefined; + } + return undefined; +} + +export function identity( + options: { + sourceRoot?: string; + readSourceFile?: (path: string) => Uint8Array; + } = {} +) { + const sourceRoot = options.sourceRoot ?? root; + const readSourceFile = options.readSourceFile ?? readFileSync; + const tracked = new Set( + command(['git', 'ls-files', '--cached', '-z'], sourceRoot).split('\0').filter(Boolean) + ); + const paths = command( + ['git', 'ls-files', '--cached', '--others', '--exclude-standard', '-z'], + sourceRoot + ) .split('\0') .filter(Boolean) .sort(); const source = createHash('sha256'); for (const path of paths) { - const absolute = join(root, path); - source.update( - JSON.stringify([path, existsSync(absolute) ? sha256(readFileSync(absolute)) : 'deleted']) - ); + const absolute = join(sourceRoot, path); + let entry: string; + try { + entry = sha256(readSourceFile(absolute)); + } catch (error) { + const code = errorCode(error); + if (code === 'ENOENT') { + entry = 'deleted'; + } else if ((code === 'EACCES' || code === 'EPERM') && !tracked.has(path)) { + entry = 'unreadable'; + } else { + throw error; + } + } + source.update(JSON.stringify([path, entry])); } const addon = join(root, 'apps/stock/engine/dist/engine.node'); const nativeSha256 = sha256(readFileSync(addon)); @@ -285,12 +317,12 @@ export function identity() { }; return { source: { - commit: command(['git', 'rev-parse', 'HEAD']), - dirty: command(['git', 'status', '--porcelain']).length > 0, + commit: command(['git', 'rev-parse', 'HEAD'], sourceRoot), + dirty: command(['git', 'status', '--porcelain'], sourceRoot).length > 0, contentSha256: source.digest('hex'), files: paths.length, scope: - 'Tracked and nonignored untracked file paths/content, including dirty changes; generated ignored artifacts excluded.', + 'Tracked and nonignored untracked file paths/content, including dirty changes; unreadable untracked files are hashed by path with an unreadable marker; generated ignored artifacts excluded.', }, native: { path: addon, diff --git a/scripts/test/benchmark-research.test.ts b/scripts/test/benchmark-research.test.ts index a4ed2b11..0d98fd7b 100644 --- a/scripts/test/benchmark-research.test.ts +++ b/scripts/test/benchmark-research.test.ts @@ -1,13 +1,71 @@ import { describe, expect, test } from 'bun:test'; +import { chmodSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; import { prepareDataset } from '../../apps/stock/orchestrator/src/data/historical-dataset'; import { economicHash, + identity, parameters, researchFixture, unavailable, verifyRepeats, } from '../benchmark-research'; +function runGit(cwd: string, args: string[]): void { + const result = Bun.spawnSync(['git', ...args], { + cwd, + stdout: 'pipe', + stderr: 'pipe', + env: { + ...process.env, + GIT_CONFIG_NOSYSTEM: '1', + GIT_CONFIG_GLOBAL: '/dev/null', + }, + }); + if (result.exitCode !== 0) { + throw new Error(`git ${args.join(' ')} failed: ${result.stderr.toString()}`); + } +} + +function withTempGitRepo(fn: (repoDir: string, protectForCleanup: (path: string) => void) => T): T { + const repoDir = mkdtempSync(join(tmpdir(), 'stock-bot-benchmark-identity-')); + const chmodPaths: string[] = []; + const protectForCleanup = (path: string) => { + chmodPaths.push(path); + }; + try { + runGit(repoDir, ['init']); + writeFileSync(join(repoDir, 'tracked.txt'), 'tracked-v1\n'); + runGit(repoDir, ['add', 'tracked.txt']); + runGit(repoDir, [ + '-c', + 'user.name=Test User', + '-c', + 'user.email=test@example.com', + 'commit', + '-m', + 'initial', + ]); + return fn(repoDir, protectForCleanup); + } finally { + for (const path of chmodPaths) { + try { + chmodSync(path, 0o600); + } catch { + // Ignore if file was removed during the test. + } + } + rmSync(repoDir, { recursive: true, force: true }); + } +} + +function fsError(code: string, path: string): NodeJS.ErrnoException { + const error = new Error(`${code}: ${path}`) as NodeJS.ErrnoException; + error.code = code; + return error; +} + describe('existing-path research benchmark', () => { test('fixture is seeded, ordered, hash-verified and detached by real dataset preparation', async () => { for (const assets of [1, 10]) { @@ -142,4 +200,126 @@ describe('existing-path research benchmark', () => { } } }); + + test('identity hashes unreadable untracked files deterministically while throwing on tracked or non-permission errors', () => { + withTempGitRepo(repoDir => { + const untrackedPath = join(repoDir, '.bash_profile'); + const trackedPath = join(repoDir, 'tracked.txt'); + writeFileSync(untrackedPath, 'placeholder\n'); + + for (const code of ['EACCES', 'EPERM'] as const) { + const readSourceFile = (path: string) => { + if (path === untrackedPath) { + throw fsError(code, path); + } + return readFileSync(path); + }; + + const first = identity({ sourceRoot: repoDir, readSourceFile }); + const second = identity({ sourceRoot: repoDir, readSourceFile }); + expect(Object.keys(first)).toEqual(['source', 'native', 'runtime', 'host']); + expect(first.source.contentSha256).toBe(second.source.contentSha256); + expect(first.source.files).toBe(2); + expect(first.source.dirty).toBe(true); + expect(first.source.scope).toContain('unreadable'); + + // Changing a readable file changes contentSha256. + writeFileSync(trackedPath, `tracked-${code}\n`); + const afterReadableEdit = identity({ sourceRoot: repoDir, readSourceFile }); + expect(afterReadableEdit.source.contentSha256).not.toBe(first.source.contentSha256); + + // Tracked files still throw EACCES / EPERM. + expect(() => + identity({ + sourceRoot: repoDir, + readSourceFile: path => { + if (path === trackedPath) { + throw fsError(code, path); + } + return readFileSync(path); + }, + }) + ).toThrow(code); + } + + // Non-permission errors on untracked files still throw. + expect(() => + identity({ + sourceRoot: repoDir, + readSourceFile: path => { + if (path === untrackedPath) { + throw fsError('EIO', path); + } + return readFileSync(path); + }, + }) + ).toThrow('EIO'); + + // Renaming or removing the unreadable untracked file changes contentSha256. + const beforeRename = identity({ + sourceRoot: repoDir, + readSourceFile: path => { + if (path === untrackedPath) { + throw fsError('EACCES', path); + } + return readFileSync(path); + }, + }); + const renamedPath = join(repoDir, '.bash_profile_renamed'); + renameSync(untrackedPath, renamedPath); + const afterRename = identity({ + sourceRoot: repoDir, + readSourceFile: path => { + if (path === renamedPath) { + throw fsError('EACCES', path); + } + return readFileSync(path); + }, + }); + expect(afterRename.source.contentSha256).not.toBe(beforeRename.source.contentSha256); + + rmSync(renamedPath); + const afterRemove = identity({ sourceRoot: repoDir }); + expect(afterRemove.source.contentSha256).not.toBe(afterRename.source.contentSha256); + expect(afterRemove.source.files).toBe(1); + }); + }); + + test('identity handles real chmod 000 untracked files and rejects chmod 000 tracked files', () => { + if (process.getuid?.() === 0) { + return; + } + withTempGitRepo((repoDir, protectForCleanup) => { + const trackedPath = join(repoDir, 'tracked.txt'); + const untrackedPath = join(repoDir, 'unreadable-untracked.txt'); + writeFileSync(untrackedPath, 'secret\n'); + chmodSync(untrackedPath, 0o000); + protectForCleanup(untrackedPath); + + const first = identity({ sourceRoot: repoDir }); + const second = identity({ sourceRoot: repoDir }); + expect(first.source.contentSha256).toBe(second.source.contentSha256); + expect(first.source.files).toBe(2); + + writeFileSync(trackedPath, 'tracked-v2\n'); + const afterEdit = identity({ sourceRoot: repoDir }); + expect(afterEdit.source.contentSha256).not.toBe(first.source.contentSha256); + + chmodSync(trackedPath, 0o000); + protectForCleanup(trackedPath); + expect(() => identity({ sourceRoot: repoDir })).toThrow(/EACCES|permission denied/i); + }); + }); + + test('identity hashes deleted unstaged tracked files with the deleted marker', () => { + withTempGitRepo(repoDir => { + const trackedPath = join(repoDir, 'tracked.txt'); + const beforeDelete = identity({ sourceRoot: repoDir }); + rmSync(trackedPath); + const afterDelete = identity({ sourceRoot: repoDir }); + expect(afterDelete.source.contentSha256).not.toBe(beforeDelete.source.contentSha256); + expect(afterDelete.source.files).toBe(1); + expect(afterDelete.source.dirty).toBe(true); + }); + }); });