diff --git a/src/commands/ci/select-baseline-scan.mts b/src/commands/ci/select-baseline-scan.mts index 86d01af39..7e74bbcfe 100644 --- a/src/commands/ci/select-baseline-scan.mts +++ b/src/commands/ci/select-baseline-scan.mts @@ -1,3 +1,5 @@ +import { debugFn } from '../../utils/debug.mts' +import { spawn } from '../../utils/spawn.mts' import { fetchOrgFullScanList } from '../scan/fetch-list-scans.mts' import type { CResult } from '../../types.mts' @@ -10,19 +12,147 @@ export type SelectBaselineScanConfig = { repo: string } +const ANCESTOR_WALK_MAX_DEPTH = 100 +const SCAN_LOOKUP_PAGE_SIZE = 100 +const SCAN_LOOKUP_MAX_PAGES = 100 + +function isUsableScan( + scan: FullScanItem, +): scan is FullScanItem & { commit_hash: string; id: string } { + return Boolean( + typeof scan.id === 'string' && + scan.id && + !(scan as FullScanItem & { tmp?: boolean }).tmp && + typeof scan.commit_hash === 'string' && + scan.commit_hash, + ) +} + +function getNextScanPage( + nextPage: number | null | undefined, + currentPage: number, + resultCount: number, +): CResult { + if ( + resultCount < SCAN_LOOKUP_PAGE_SIZE || + nextPage === undefined || + nextPage === null || + nextPage === 0 + ) { + return { ok: true, data: undefined } + } + if (!Number.isSafeInteger(nextPage) || nextPage <= currentPage) { + return { + ok: false, + message: 'Cannot select PR scan baseline', + cause: `Full-scan listing did not advance to a new page (nextPage=${String(nextPage)}).`, + } + } + return { ok: true, data: nextPage } +} + export function findBaselineScan( scans: FullScanItem[], commitHash: string, ): FullScanItem | undefined { - return scans.find(scan => scan.commit_hash === commitHash) + return scans.find( + scan => scan.commit_hash === commitHash && isUsableScan(scan), + ) +} + +async function firstParentCommits( + commitHash: string, + cwd = process.cwd(), +): Promise { + const resolved = await spawn( + 'git', + ['rev-parse', '--verify', '--end-of-options', `${commitHash}^{commit}`], + { cwd }, + ) + const expectedCommit = resolved.stdout.trim() + if (!expectedCommit) { + throw new Error('Empty git rev-parse result') + } + const result = await spawn( + 'git', + [ + 'rev-list', + '--first-parent', + `--max-count=${ANCESTOR_WALK_MAX_DEPTH}`, + '--end-of-options', + expectedCommit, + ], + { cwd }, + ) + const commits = result.stdout + .split(/\r?\n/u) + .map(commit => commit.trim()) + .filter(Boolean) + if (commits[0] !== expectedCommit) { + throw new Error('Unexpected git rev-list result') + } + return commits } -export async function selectBaselineScan({ +async function scanForCommit({ branch, commitHash, orgSlug, repo, -}: SelectBaselineScanConfig): Promise> { +}: SelectBaselineScanConfig): Promise> { + let page = 1 + for (let pageCount = 0; pageCount < SCAN_LOOKUP_MAX_PAGES; pageCount += 1) { + // eslint-disable-next-line no-await-in-loop -- Pagination must consume one page at a time. + const scansCResult = await fetchOrgFullScanList({ + branch, + commitHash, + direction: 'desc', + from_time: '', + orgSlug, + page, + perPage: SCAN_LOOKUP_PAGE_SIZE, + repo, + sort: 'created_at', + }) + if (!scansCResult.ok) { + return scansCResult + } + const scan = findBaselineScan(scansCResult.data.results, commitHash) + if (scan) { + return { ok: true, data: scan } + } + const results = scansCResult.data.results + const nextPageCResult = getNextScanPage( + ( + scansCResult.data as typeof scansCResult.data & { + nextPage?: number | null + } + ).nextPage, + page, + results.length, + ) + if (!nextPageCResult.ok) { + return nextPageCResult + } + if (nextPageCResult.data === undefined) { + break + } + page = nextPageCResult.data + if (pageCount === SCAN_LOOKUP_MAX_PAGES - 1) { + return { + ok: false, + message: 'Cannot select PR scan baseline', + cause: `Full-scan listing exceeded ${SCAN_LOOKUP_MAX_PAGES} pages while searching for commit ${commitHash}.`, + } + } + } + return { ok: true, data: undefined } +} + +export async function selectBaselineScan( + config: SelectBaselineScanConfig, +): Promise> { + const { branch, commitHash, repo } = config if (!commitHash) { return { ok: false, @@ -30,28 +160,44 @@ export async function selectBaselineScan({ cause: 'The CI checkout does not provide a commit SHA.', } } - - const scansCResult = await fetchOrgFullScanList({ - branch, - commitHash, - direction: 'desc', - from_time: '', - orgSlug, - page: 1, - perPage: 1, - repo, - sort: 'created_at', - }) - if (!scansCResult.ok) { - return scansCResult + const exact = await scanForCommit(config) + if (!exact.ok) { + return exact + } + if (exact.data) { + return { ok: true, data: exact.data } + } + let history: string[] + try { + history = await firstParentCommits(commitHash) + } catch (error) { + debugFn( + 'debug', + `Unable to walk first-parent history from ${commitHash}`, + error, + ) + return { + ok: false, + message: 'Cannot read PR base commit history', + cause: `Fetch the base commit ${commitHash} and its first-parent history into the CI checkout before retrying.`, + } + } + for (const [index, ancestor] of history.slice(1).entries()) { + // eslint-disable-next-line no-await-in-loop -- Query nearest first and stop once a baseline is found. + const result = await scanForCommit({ ...config, commitHash: ancestor }) + if (!result.ok) { + return result + } + if (result.data) { + console.error( + `No scan exists for PR base commit ${commitHash}; using its scanned first-parent ancestor ${ancestor} as the baseline (${index + 1} commit(s) earlier). The diff is wider than the PR base.`, + ) + return { ok: true, data: result.data } + } + } + return { + ok: false, + message: 'No matching PR scan baseline found', + cause: `No scan exists for commit ${commitHash} or a scanned first-parent ancestor within ${ANCESTOR_WALK_MAX_DEPTH} commits on ${repo}/${branch}. Run a scan for the base commit first.`, } - - const scan = findBaselineScan(scansCResult.data.results, commitHash) - return scan - ? { ok: true, data: scan } - : { - ok: false, - message: 'No matching PR scan baseline found', - cause: `No scan exists for commit ${commitHash} on ${repo}/${branch}. Run a scan for the base commit first.`, - } } diff --git a/test/unit/src/commands/ci/select-baseline-scan.test.mts b/test/unit/src/commands/ci/select-baseline-scan.test.mts index 89bad997a..da32788e1 100644 --- a/test/unit/src/commands/ci/select-baseline-scan.test.mts +++ b/test/unit/src/commands/ci/select-baseline-scan.test.mts @@ -4,11 +4,15 @@ import { findBaselineScan, selectBaselineScan, } from '../../../../../src/commands/ci/select-baseline-scan.mts' +import { spawn } from '../../../../../src/utils/spawn.mts' import { fetchOrgFullScanList } from '../../../../../src/commands/scan/fetch-list-scans.mts' vi.mock('../../../../../src/commands/scan/fetch-list-scans.mts', () => ({ fetchOrgFullScanList: vi.fn(), })) +vi.mock('../../../../../src/utils/spawn.mts', () => ({ + spawn: vi.fn(), +})) const scan = { api_url: null, @@ -30,6 +34,7 @@ const scan = { describe('selectBaselineScan', () => { beforeEach(() => { vi.mocked(fetchOrgFullScanList).mockReset() + vi.mocked(spawn).mockReset() }) it('selects the exact commit when the scan list includes nearby scans', () => { @@ -58,7 +63,7 @@ describe('selectBaselineScan', () => { expect.objectContaining({ branch: 'main', commitHash: 'base-sha', - perPage: 1, + perPage: 100, repo: 'test-repo', }), ) @@ -76,7 +81,8 @@ describe('selectBaselineScan', () => { expect(fetchOrgFullScanList).not.toHaveBeenCalled() }) - it('fails closed when the exact commit has no scan', async () => { + it('fails closed when the base is a root commit without a scan', async () => { + vi.mocked(spawn).mockResolvedValue({ stdout: 'unknown-sha' } as never) vi.mocked(fetchOrgFullScanList).mockResolvedValue({ ok: true, data: { results: [scan] }, @@ -93,4 +99,159 @@ describe('selectBaselineScan', () => { message: 'No matching PR scan baseline found', }) }) + + it('asks for base history when the checkout cannot resolve the base commit', async () => { + vi.mocked(fetchOrgFullScanList).mockResolvedValueOnce({ + ok: true, + data: { results: [] }, + }) + vi.mocked(spawn).mockRejectedValueOnce(new Error('missing object')) + await expect( + selectBaselineScan({ + branch: 'main', + commitHash: 'base-sha', + orgSlug: 'test-org', + repo: 'test-repo', + }), + ).resolves.toMatchObject({ + ok: false, + message: 'Cannot read PR base commit history', + cause: expect.stringContaining('Fetch the base commit base-sha'), + }) + expect(fetchOrgFullScanList).toHaveBeenCalledTimes(1) + }) + + it('uses the nearest scanned first-parent ancestor when the exact commit is unscanned', async () => { + vi.mocked(spawn) + .mockResolvedValueOnce({ stdout: 'head-sha' } as never) + .mockResolvedValueOnce({ + stdout: 'head-sha\nparent-1\nparent-2', + } as never) + vi.mocked(fetchOrgFullScanList) + .mockResolvedValueOnce({ ok: true, data: { results: [] } }) + .mockResolvedValueOnce({ + ok: true, + data: { + results: [ + { ...scan, id: 'parent-2-scan', commit_hash: 'parent-2' }, + { ...scan, id: 'parent-1-scan', commit_hash: 'parent-1' }, + ], + }, + }) + + await expect( + selectBaselineScan({ + branch: 'main', + commitHash: 'head-sha', + orgSlug: 'test-org', + repo: 'test-repo', + }), + ).resolves.toEqual({ + ok: true, + data: { ...scan, id: 'parent-1-scan', commit_hash: 'parent-1' }, + }) + expect(fetchOrgFullScanList).toHaveBeenNthCalledWith( + 2, + expect.objectContaining({ branch: 'main', commitHash: 'parent-1' }), + ) + expect(spawn).toHaveBeenCalledWith( + 'git', + [ + 'rev-list', + '--first-parent', + '--max-count=100', + '--end-of-options', + 'head-sha', + ], + { cwd: process.cwd() }, + ) + }) + + it('skips temporary and unusable scans when selecting a baseline', async () => { + vi.mocked(spawn) + .mockResolvedValueOnce({ stdout: 'head-sha' } as never) + .mockResolvedValueOnce({ stdout: 'head-sha\nparent-sha' } as never) + vi.mocked(fetchOrgFullScanList) + .mockResolvedValueOnce({ + ok: true, + data: { + results: [ + { ...scan, id: 'temporary', commit_hash: 'head-sha', tmp: true }, + { ...scan, id: '', commit_hash: 'head-sha' }, + ], + }, + } as never) + .mockResolvedValueOnce({ + ok: true, + data: { + results: [ + { ...scan, id: 'persisted-parent', commit_hash: 'parent-sha' }, + ], + }, + }) + + await expect( + selectBaselineScan({ + branch: 'main', + commitHash: 'head-sha', + orgSlug: 'test-org', + repo: 'test-repo', + }), + ).resolves.toMatchObject({ ok: true, data: { id: 'persisted-parent' } }) + }) + + it('preserves scan-list API failures during ancestor lookup', async () => { + vi.mocked(spawn) + .mockResolvedValueOnce({ stdout: 'head-sha' } as never) + .mockResolvedValueOnce({ stdout: 'head-sha\nparent-sha' } as never) + vi.mocked(fetchOrgFullScanList) + .mockResolvedValueOnce({ ok: true, data: { results: [] } }) + .mockResolvedValueOnce({ + ok: false, + message: 'Cannot list scans', + cause: 'API unavailable', + }) + + await expect( + selectBaselineScan({ + branch: 'main', + commitHash: 'head-sha', + orgSlug: 'test-org', + repo: 'test-repo', + }), + ).resolves.toMatchObject({ + ok: false, + message: 'Cannot list scans', + cause: 'API unavailable', + }) + }) + + it('fails instead of following a repeated scan-list page', async () => { + vi.mocked(fetchOrgFullScanList).mockResolvedValue({ + ok: true, + data: { + results: Array.from({ length: 100 }, (_, index) => ({ + ...scan, + id: `temporary-${index}`, + commit_hash: 'base-sha', + tmp: true, + })), + nextPage: 1, + }, + } as never) + + await expect( + selectBaselineScan({ + branch: 'main', + commitHash: 'base-sha', + orgSlug: 'test-org', + repo: 'test-repo', + }), + ).resolves.toMatchObject({ + ok: false, + message: 'Cannot select PR scan baseline', + cause: expect.stringContaining('did not advance'), + }) + expect(spawn).not.toHaveBeenCalled() + }) })