diff --git a/package.json b/package.json index 3784d208765..5762b9e4283 100644 --- a/package.json +++ b/package.json @@ -26,7 +26,7 @@ "buffer": "6.0.3", "crypto-browserify": "3.12.1", "dayjs": "1.11.23", - "fuse.js": "7.5.0", + "fzf": "0.5.2", "js-cookie": "3.0.8", "js-yaml": "5.5.0", "json-e": "4.8.4", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 3bb399f8096..cbce7a1685f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -57,9 +57,9 @@ importers: dayjs: specifier: 1.11.23 version: 1.11.23 - fuse.js: - specifier: 7.5.0 - version: 7.5.0 + fzf: + specifier: 0.5.2 + version: 0.5.2 js-cookie: specifier: 3.0.8 version: 3.0.8 @@ -2830,9 +2830,8 @@ packages: function-bind@1.1.2: resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==} - fuse.js@7.5.0: - resolution: {integrity: sha512-sQtrEfA+ez/3G0cCZecF70oqpCRttCexYUG4mUrtWL49ULUzUyxokt5kyqwtKzj1270RaKih+hcP3qLcumccow==} - engines: {node: '>=10'} + fzf@0.5.2: + resolution: {integrity: sha512-Tt4kuxLXFKHy8KT40zwsUPUkg1CrsgY25FxA2U/j/0WgEDCk3ddc/zLTCCcbSHX9FcKtLuVaDGtGE/STWC+j3Q==} generator-function@2.0.1: resolution: {integrity: sha512-SFdFmIJi+ybC0vjlHN0ZGVGHc3lgE0DxPAT0djjVg+kjOnSqclqmj0KQ7ykTOLP6YxoqOvuAODGdcHJn+43q3g==} @@ -8085,7 +8084,7 @@ snapshots: function-bind@1.1.2: {} - fuse.js@7.5.0: {} + fzf@0.5.2: {} generator-function@2.0.1: {} diff --git a/tests/ui/job-view/Push_test.jsx b/tests/ui/job-view/Push_test.jsx index 46cfafeceac..b1be03e82f5 100644 --- a/tests/ui/job-view/Push_test.jsx +++ b/tests/ui/job-view/Push_test.jsx @@ -1,6 +1,12 @@ - import fetchMock from 'fetch-mock'; -import { render, cleanup, waitFor } from '@testing-library/react'; +import { + render, + cleanup, + fireEvent, + screen, + waitFor, +} from '@testing-library/react'; +import { MemoryRouter } from 'react-router'; import { gzip } from 'pako'; import { getProjectUrl, replaceLocation } from '../../../ui/helpers/location'; @@ -13,6 +19,8 @@ import Push, { } from '../../../ui/job-view/pushes/Push'; import { getApiUrl } from '../../../ui/helpers/url'; import { findInstance } from '../../../ui/helpers/job'; +import RunnableJobModel from '../../../ui/models/runnableJob'; +import { usePushesStore } from '../../../ui/shared/stores/pushesStore'; const manifestsByTask = { 'test-linux1804-64/debug-mochitest-devtools-chrome-e10s-1': [ @@ -106,6 +114,7 @@ describe('Push', () => { const repoName = 'autoland'; const currentRepo = { name: repoName, + tc_root_url: 'https://firefox-ci-tc.services.mozilla.com', getRevisionHref: () => 'foo', getPushLogHref: () => 'foo', }; @@ -158,6 +167,149 @@ describe('Push', () => { replaceLocation({}); }); + test.each(['response', 'worker'])( + 'Loads picker metadata, retries after a %s error, and caches success on the push', + async (failure) => { + const originalWorker = global.Worker; + const originalDecisionTasks = usePushesStore.getState().decisionTaskMap; + const decisionTask = { id: 'picker-decision-task', run: 2 }; + const main = 'test-linux64/opt-mochitest-media-1'; + const second = 'test-linux64/opt-mochitest-media-2'; + const excluded = 'toolchain-linux64-clang'; + const getList = jest + .spyOn(RunnableJobModel, 'getList') + .mockResolvedValue( + [second, excluded, main].map((job_type_name) => ({ job_type_name })), + ); + const graphRequests = jest.fn(); + const terminate = jest.fn(); + let requests = 0; + global.Worker = class { + constructor(url) { + this.isMetadataWorker = String(url).includes( + 'runnableJobMetadata.worker.js', + ); + } + + postMessage(url) { + if (!this.isMetadataWorker) return; + graphRequests(url); + requests += 1; + if (requests === 1) { + if (failure === 'worker') + this.onerror({ message: 'Worker failed' }); + else this.onmessage({ data: { error: 'Artifact missing' } }); + } else { + this.onmessage({ + data: { + metadata: Object.fromEntries( + [main, second].map((label) => [ + label, + { + chunkPattern: 'test-linux64/opt-mochitest-media-*', + tier: 1, + }, + ]), + ), + }, + }); + } + } + + terminate() { + if (this.isMetadataWorker) terminate(); + } + }; + usePushesStore.setState({ decisionTaskMap: { [push.id]: decisionTask } }); + + const openPicker = async () => { + fireEvent.click(screen.getByTestId('push-action-menu-button')); + fireEvent.click(screen.getByText('Add new jobs (Search)')); + return screen.findByRole('dialog'); + }; + const closePicker = async () => { + fireEvent.click(screen.getByRole('button', { name: 'Cancel' })); + await waitFor(() => + expect(screen.queryByRole('dialog')).not.toBeInTheDocument(), + ); + }; + try { + render({testPush(new FilterModel())}); + await openPicker(); + expect(graphRequests).not.toHaveBeenCalled(); + const loadMetadata = () => + fireEvent.click( + screen.getByRole('button', { + name: 'Load job filters and test paths', + }), + ); + loadMetadata(); + await waitFor(() => expect(graphRequests).toHaveBeenCalledTimes(1)); + expect(screen.getByRole('option', { name: main })).toBeInTheDocument(); + expect( + screen.queryByRole('option', { name: excluded }), + ).not.toBeInTheDocument(); + await closePicker(); + + await openPicker(); + expect(graphRequests).toHaveBeenCalledTimes(1); + loadMetadata(); + expect( + await screen.findByRole('option', { + name: 'test-linux64/opt-mochitest-media-*', + }), + ).toBeInTheDocument(); + fireEvent.click( + screen.getByRole('checkbox', { name: 'Use full job list' }), + ); + expect( + screen.getByRole('option', { name: excluded }), + ).toBeInTheDocument(); + await closePicker(); + + await openPicker(); + expect( + screen.getByRole('option', { + name: 'test-linux64/opt-mochitest-media-*', + }), + ).toBeInTheDocument(); + expect(getList).toHaveBeenCalledTimes(3); + expect(getList).toHaveBeenLastCalledWith(currentRepo, { decisionTask }); + expect(graphRequests).toHaveBeenCalledTimes(2); + expect(graphRequests).toHaveBeenLastCalledWith( + `${currentRepo.tc_root_url}/api/queue/v1/task/${decisionTask.id}/runs/2/artifacts/public/full-task-graph.json`, + ); + expect(terminate).toHaveBeenCalledTimes(2); + } finally { + cleanup(); + global.Worker = originalWorker; + getList.mockRestore(); + usePushesStore.setState({ decisionTaskMap: originalDecisionTasks }); + } + }, + ); + + test('Keeps the picker closed if runnable jobs cannot be loaded', async () => { + const getList = jest + .spyOn(RunnableJobModel, 'getList') + .mockRejectedValue(new Error('Unavailable')); + const originalDecisionTasks = usePushesStore.getState().decisionTaskMap; + usePushesStore.setState({ + decisionTaskMap: { [push.id]: { id: 'picker-decision-task', run: 0 } }, + }); + try { + render({testPush(new FilterModel())}); + fireEvent.click(screen.getByTestId('push-action-menu-button')); + fireEvent.click(screen.getByText('Add new jobs (Search)')); + await waitFor(() => expect(getList).toHaveBeenCalled()); + expect(screen.queryByRole('dialog')).not.toBeInTheDocument(); + } finally { + cleanup(); + getList.mockRestore(); + usePushesStore.setState({ decisionTaskMap: originalDecisionTasks }); + } + }); + // eslint-disable-next-line jest/no-disabled-tests test.skip('jobs should have test_path field to filter', async () => { const { getByText } = render(testPush(new FilterModel())); diff --git a/tests/ui/job-view/fuzzy_test.jsx b/tests/ui/job-view/fuzzy_test.jsx index 23284ed4898..96206fdec23 100644 --- a/tests/ui/job-view/fuzzy_test.jsx +++ b/tests/ui/job-view/fuzzy_test.jsx @@ -1,13 +1,47 @@ - -import { render, fireEvent, waitFor } from '@testing-library/react'; +import { + act, + render, + fireEvent, + waitFor, + within, +} from '@testing-library/react'; +import { cloneElement } from 'react'; import fuzzyJobList from '../mock/job_list/fuzzy_jobs/fuzzyJobList.json'; import initialJobList from '../mock/job_list/fuzzy_jobs/initial_job_list.json'; import searchLinuxResults from '../mock/job_list/fuzzy_jobs/search_linux_results.json'; import searchDebugResults from '../mock/job_list/fuzzy_jobs/search_debug_results.json'; import FuzzyJobFinder from '../../../ui/job-view/pushes/FuzzyJobFinder'; +import PushModel from '../../../ui/models/push'; +import TaskclusterModel from '../../../ui/models/taskcluster'; +import { getPickerMetadata } from '../../../ui/job-view/pushes/runnableJobMetadata.worker'; +import { + normalizeTestPaths, + planPathJobs, +} from '../../../ui/job-view/pushes/runnableJobPaths'; +import { createSearchHandler } from '../../../ui/job-view/pushes/runnableJobSearch.worker'; + +class SearchWorker { + handleMessage = createSearchHandler((data) => this.onmessage({ data })); + + postMessage(data) { + setTimeout(() => this.handleMessage?.({ data }), 0); + } + + terminate() { + this.handleMessage = null; + } +} describe('FuzzyJobFinder', () => { + const originalWorker = global.Worker; + beforeEach(() => { + global.Worker = SearchWorker; + }); + afterEach(() => { + global.Worker = originalWorker; + }); + const isOpen = true; const decisionTaskId = 'YHKMjYZeSSmEZTrAPdRIag'; const id = 705037; @@ -46,6 +80,503 @@ describe('FuzzyJobFinder', () => { /> ); + test.each([ + ['test-linux2404-64/opt-mochitest-media-2', null, false], + ['test-linux2404-64/opt-mochitest-browser-media', null, false], + ['test-linux2404-64/opt-mochitest-browser-a11y', null, false], + ['test-linux2404-64/opt-mochitest-media-nogpu-2', 'no-gpu', true], + [ + 'test-linux2404-64/opt-mochitest-browser-chrome-swr-2', + 'webrender-sw', + true, + ], + [ + 'test-linux2404-64/opt-mochitest-browser-chrome-swr-uipc-2', + 'webrender-sw+urlbar-ipc', + true, + ], + ['test-windows11-64/opt-xpcshell-msix', 'msix', true], + [ + 'test-linux2404-64/opt-mochitest-browser-chrome-a11y-checks', + 'a11y-checks', + true, + ], + ['test-linux2404-64/opt-mochitest-browser-chrome-2-cf', null, true], + ['test-linux2404-64/opt-mochitest-plain-swr-extra', null, false], + ['test-linux2404-64-asan/opt-mochitest-media', null, true], + ['test-variant-without-a-known-suffix', 'future-variant', true], + ])('classifies %s using Gecko metadata', (label, variant, specialized) => { + const metadata = getPickerMetadata({ + [label]: { + attributes: { unittest_variant: variant }, + task: { extra: { treeherder: { tier: 1 }, chunks: { total: 3 } } }, + }, + }); + expect(metadata[label].specialized).toBe(specialized); + }); + + test.each(['bc1', 'M(bc)', 'm(BC1)'])( + 'Finds jobs by symbol %s', + async (query) => { + const jobs = [ + { name: 'linux-chrome-1', symbol: 'bc1', groupsymbol: 'M' }, + { name: 'linux-chrome', symbol: 'bc', groupsymbol: 'M' }, + ]; + const { getByTitle, getAllByRole } = render( + cloneElement(testFuzzyJobFinder, { + jobList: jobs, + filteredJobList: jobs, + }), + ); + + fireEvent.change(getByTitle('Filter the list of runnable jobs'), { + target: { value: query }, + }); + await waitFor(() => + expect( + getAllByRole('option').map((option) => option.textContent), + ).toEqual([query === 'M(bc)' ? 'linux-chrome' : 'linux-chrome-1']), + ); + }, + ); + + test('Finds a chunk group by a later chunk’s symbol', async () => { + const chunkPattern = 'linux-chrome-*'; + const jobs = [ + { name: 'linux-chrome-1', symbol: 'bc1', chunkPattern }, + { name: 'linux-chrome-2', symbol: 'bc2', chunkPattern }, + ]; + const { getByTitle, getByRole } = render( + cloneElement(testFuzzyJobFinder, { + jobList: jobs, + filteredJobList: jobs, + }), + ); + + fireEvent.change(getByTitle('Filter the list of runnable jobs'), { + target: { value: 'bc2' }, + }); + await waitFor(() => + expect(getByRole('button', { name: 'Add all' })).toBeEnabled(), + ); + expect(getByRole('option', { name: chunkPattern })).toBeInTheDocument(); + }); + + test('Shows an empty list while runnable jobs are unavailable', () => { + const { getByText, getByRole } = render( + cloneElement(testFuzzyJobFinder, { + jobList: undefined, + filteredJobList: undefined, + }), + ); + expect(getByText('Runnable Jobs [0]')).toBeInTheDocument(); + fireEvent.click(getByRole('checkbox', { name: 'Use full job list' })); + expect(getByText('Runnable Jobs [0]')).toBeInTheDocument(); + }); + + test('Groups CLI chunk patterns and keeps tier 2 and 3 hidden when showing the full list', () => { + const jobs = [ + { name: 'mochitest-media-1', tier: 1, chunkPattern: 'mochitest-media-*' }, + { name: 'mochitest-media-2', tier: 1, chunkPattern: 'mochitest-media-*' }, + { name: 'tier-2-job', tier: 2 }, + { name: 'tier-3-job', tier: 3 }, + { name: 'specialized-job', tier: 1, specialized: true }, + ]; + const { getByRole, queryAllByTestId } = render( + cloneElement(testFuzzyJobFinder, { + jobList: jobs, + filteredJobList: jobs, + }), + ); + const labels = () => + queryAllByTestId('fuzzyList').map((row) => row.textContent); + expect(labels()).toEqual(['mochitest-media-*']); + fireEvent.click(getByRole('checkbox', { name: 'Use full job list' })); + expect(labels()).toEqual(['mochitest-media-*']); + fireEvent.click(getByRole('button', { name: 'Add all' })); + expect( + getByRole('button', { name: 'Trigger (2) Selected Jobs' }), + ).toBeEnabled(); + fireEvent.click(getByRole('checkbox', { name: 'Show chunk numbers' })); + expect(labels()).toEqual(['mochitest-media-1', 'mochitest-media-2']); + fireEvent.click(getByRole('checkbox', { name: 'Show specialized jobs' })); + expect(new Set(labels())).toEqual( + new Set([ + 'mochitest-media-1', + 'mochitest-media-2', + 'specialized-job', + 'tier-2-job', + 'tier-3-job', + ]), + ); + }); + + test('Only tests with existing builds matches the exact dependency on this push', async () => { + const trigger = jest + .spyOn(PushModel, 'triggerNewJobs') + .mockResolvedValue('Requested'); + const jobs = [ + { name: 'test-opt', buildDependency: 'build-linux64/opt' }, + { name: 'test-debug', buildDependency: 'build-linux64/debug' }, + ]; + try { + const { getByRole, queryAllByTestId } = render( + cloneElement(testFuzzyJobFinder, { + jobList: jobs, + filteredJobList: jobs, + pushJobs: [{ job_type_name: 'build-linux64/opt', result: 'success' }], + }), + ); + fireEvent.click(getByRole('button', { name: 'Add all' })); + fireEvent.click( + getByRole('checkbox', { name: 'Only tests with existing builds' }), + ); + expect( + queryAllByTestId('fuzzyList').map((row) => row.textContent), + ).toEqual(['test-opt']); + await act(async () => + fireEvent.click( + getByRole('button', { name: 'Trigger (1) Selected Jobs' }), + ), + ); + expect(trigger).toHaveBeenCalledWith( + ['test-opt'], + decisionTaskId, + currentRepo, + ); + } finally { + trigger.mockRestore(); + } + }); + + test('Filters by existing builds and submits only the chunks matching test paths', async () => { + const trigger = jest + .spyOn(PushModel, 'triggerJobsForPaths') + .mockResolvedValue({ + submitted: [{ label: 'test-a', taskId: 'task-id' }], + failed: [], + }); + const suite = 'mochitest-browser-chrome'; + const revision = 'the-revision'; + const jobs = [ + { + name: 'test-a', + symbol: 'bc', + buildDependency: 'build-a', + pathScope: { + suite, + manifests: ['browser/components/one/browser.toml'], + }, + }, + { + name: 'test-unused-chunk', + symbol: 'bc2', + buildDependency: 'build-a', + pathScope: { + suite, + manifests: ['browser/components/unrelated/browser.toml'], + }, + }, + { + name: 'test-b', + symbol: 'bc', + buildDependency: 'build-b', + pathScope: { + suite, + manifests: ['browser/components/two/browser.toml'], + }, + }, + ]; + try { + const { getByRole, getByLabelText, findByText, queryAllByTestId } = + render( + cloneElement(testFuzzyJobFinder, { + revision, + jobList: jobs, + filteredJobList: jobs, + pushJobs: [{ job_type_name: 'build-a', result: 'success' }], + }), + ); + fireEvent.click( + getByRole('checkbox', { name: 'Only tests with existing builds' }), + ); + expect( + queryAllByTestId('fuzzyList').map((row) => row.textContent), + ).toEqual(['test-a', 'test-unused-chunk']); + fireEvent.click(getByRole('button', { name: 'Add all' })); + const input = getByLabelText('Test paths'); + fireEvent.change(input, { target: { value: 'browser/components/one' } }); + await findByText('1 task matches the test paths'); + + fireEvent.change(input, { target: { value: 'browser/components/two' } }); + expect( + getByRole('button', { name: 'Trigger (0) Selected Jobs' }), + ).toBeDisabled(); + expect(getByRole('alert')).toHaveTextContent( + 'No selected test groups match', + ); + + fireEvent.change(input, { target: { value: 'browser/components/one' } }); + const triggerButton = getByRole('button', { + name: 'Trigger (1) Selected Jobs', + }); + await act(async () => fireEvent.click(triggerButton)); + expect(trigger).toHaveBeenCalledWith( + [ + { + label: 'test-a', + suite, + symbol: 'bc', + paths: ['browser/components/one/browser.toml'], + requestedPaths: ['browser/components/one'], + }, + ], + decisionTaskId, + currentRepo, + revision, + ); + } finally { + trigger.mockRestore(); + } + }); + + test('Retries only failed path jobs with their original paths after partial submission', async () => { + const load = jest.spyOn(TaskclusterModel, 'load').mockResolvedValue({ + actions: [{ name: 'backfill-task' }], + staticActionVariables: {}, + }); + const submit = jest + .spyOn(TaskclusterModel, 'submit') + .mockResolvedValueOnce('first-action') + .mockRejectedValueOnce(new Error('Could not request second action')) + .mockResolvedValueOnce('retried-action'); + const jobs = ['first', 'second'].map((name) => ({ + name, + symbol: 'X', + pathScope: { + suite: 'xpcshell', + manifests: [`dom/${name}/xpcshell.toml`], + }, + })); + const toggle = jest.fn(); + try { + const { getByRole, getByLabelText } = render( + cloneElement(testFuzzyJobFinder, { + revision: 'the-revision', + jobList: jobs, + filteredJobList: jobs, + toggle, + }), + ); + fireEvent.click(getByRole('button', { name: 'Add all' })); + const input = getByLabelText('Test paths'); + fireEvent.change(input, { target: { value: '../invalid' } }); + expect(getByRole('alert')).toHaveTextContent( + 'Expected a repository-relative test path', + ); + fireEvent.change(input, { target: { value: 'dom/first\ndom/second' } }); + + await act(async () => + fireEvent.click( + getByRole('button', { name: 'Trigger (2) Selected Jobs' }), + ), + ); + expect(toggle).not.toHaveBeenCalled(); + expect(input).toHaveValue('dom/second'); + const selectedJobs = within(document.getElementById('removeJobsGroup')); + const selectedOption = selectedJobs.getByRole('option', { + name: 'second', + }); + selectedOption.selected = true; + fireEvent.change(selectedJobs.getByRole('listbox')); + expect(getByRole('button', { name: 'Remove selected' })).toBeEnabled(); + + await act(async () => + fireEvent.click( + getByRole('button', { name: 'Trigger (1) Selected Jobs' }), + ), + ); + expect(submit.mock.calls.map(([request]) => request.input.label)).toEqual( + ['first', 'second', 'second'], + ); + expect(submit.mock.calls.at(-1)[0].input.test_manifests).toEqual({ + xpcshell: ['dom/second/xpcshell.toml'], + }); + expect(toggle).toHaveBeenCalledTimes(1); + } finally { + submit.mockRestore(); + load.mockRestore(); + } + }); + + test('Allows retry when submitting selected jobs fails', async () => { + const trigger = jest + .spyOn(PushModel, 'triggerNewJobs') + .mockRejectedValueOnce(new Error('Taskcluster unavailable')); + const toggle = jest.fn(); + const jobs = [{ name: 'one-job' }]; + try { + const { getByRole } = render( + cloneElement(testFuzzyJobFinder, { + jobList: jobs, + filteredJobList: jobs, + toggle, + }), + ); + fireEvent.click(getByRole('button', { name: 'Add all' })); + const submit = getByRole('button', { name: 'Trigger (1) Selected Jobs' }); + await act(async () => fireEvent.click(submit)); + expect(trigger).toHaveBeenCalledTimes(1); + expect(submit).toBeEnabled(); + expect(toggle).not.toHaveBeenCalled(); + } finally { + trigger.mockRestore(); + } + }); + + test('Uses the push backfill action with the existing manifest payload contract', async () => { + const action = { name: 'backfill-task' }; + const load = jest.spyOn(TaskclusterModel, 'load').mockResolvedValue({ + actions: [action], + staticActionVariables: {}, + }); + const submit = jest + .spyOn(TaskclusterModel, 'submit') + .mockResolvedValue('action-task-id'); + const plan = [ + { + label: 'test-label', + suite: 'xpcshell', + symbol: 'X1', + paths: ['dom/test/xpcshell.toml'], + }, + ]; + try { + await expect( + PushModel.triggerJobsForPaths( + plan, + decisionTaskId, + currentRepo, + 'revision', + ), + ).resolves.toEqual({ + failed: [], + submitted: [{ label: 'test-label', taskId: 'action-task-id' }], + }); + expect(submit).toHaveBeenCalledWith( + expect.objectContaining({ + action, + decisionTaskId, + input: { + label: 'test-label', + revision: 'revision', + symbol: 'X1', + test_manifests: { xpcshell: ['dom/test/xpcshell.toml'] }, + times: 1, + retrigger: true, + }, + }), + ); + } finally { + submit.mockRestore(); + load.mockRestore(); + } + }); + + test('Reads picker metadata from the published full task graph', () => { + const label = 'test-linux2404-64/opt-mochitest-browser-chrome-swr-1'; + const manifests = ['browser/components/one/browser.toml']; + expect( + getPickerMetadata({ + [label]: { + attributes: { + unittest_suite: 'mochitest-browser-chrome', + unittest_variant: 'webrender-sw', + test_platform: 'linux2404-64/opt', + test_manifests: manifests, + }, + dependencies: { build: 'build-linux64/opt' }, + task: { + extra: { + treeherder: { tier: 2 }, + chunks: { current: 1, total: 2 }, + }, + payload: { env: { MOZHARNESS_TEST_PATHS: '{}' } }, + }, + }, + })[label], + ).toEqual({ + tier: 2, + chunkPattern: 'test-linux2404-64/opt-mochitest-browser-chrome-swr-*', + specialized: true, + buildDependency: 'build-linux64/opt', + pathScope: { suite: 'mochitest-browser-chrome', manifests }, + }); + }); + + test('Matches paths at directory boundaries and narrows WPT groups', () => { + expect(normalizeTestPaths('../outside').error).toBeTruthy(); + expect(normalizeTestPaths('./browser/components/one/')).toEqual({ + paths: ['browser/components/one'], + }); + const paths = [ + 'testing/web-platform/tests/css/subdir', + 'browser/components/one', + ]; + const { plan, unmatched } = planPathJobs( + [ + { + name: 'wpt', + symbol: 'w', + pathScope: { suite: 'web-platform-tests', manifests: ['/css'] }, + }, + { + name: 'mochitest', + symbol: 'm', + pathScope: { + suite: 'mochitest-browser-chrome', + manifests: ['browser/components/one-more/browser.toml'], + }, + }, + ], + paths, + ); + expect(plan).toEqual([ + { + label: 'wpt', + symbol: 'w', + suite: 'web-platform-tests', + paths: [paths[0]], + requestedPaths: [paths[0]], + }, + ]); + expect(unmatched).toEqual([paths[1]]); + }); + + test('Matches Mozilla-specific WPT paths against the published test group', () => { + const path = 'testing/web-platform/mozilla/tests/fetch'; + const job = { + name: 'test-wpt-mozilla-1', + symbol: 'W1', + pathScope: { + suite: 'web-platform-tests', + manifests: ['/_mozilla/fetch/api'], + }, + }; + expect(planPathJobs([job], [path])).toEqual({ + plan: [ + { + label: job.name, + suite: 'web-platform-tests', + symbol: 'W1', + paths: ['/_mozilla/fetch/api'], + requestedPaths: [path], + }, + ], + unmatched: [], + }); + }); + test('Fuzzy search gives expected results', async () => { const { getByTitle, queryAllByTestId } = await render(testFuzzyJobFinder); const inputElement = getByTitle('Filter the list of runnable jobs'); @@ -62,8 +593,6 @@ describe('FuzzyJobFinder', () => { await fireEvent.change(inputElement, { target: { value: 'linux' } }); expect(inputElement.value).toBe('linux'); - await fireEvent.keyDown(inputElement, { key: 'Enter', code: 'Enter' }); - await waitFor(() => { expect(queryAllByTestId('fuzzyList')).toHaveLength(26); const fuzzySearchArray = queryAllByTestId('fuzzyList').map( @@ -72,6 +601,7 @@ describe('FuzzyJobFinder', () => { expect(fuzzySearchArray).toStrictEqual( expect.arrayContaining(searchLinuxResults), ); + expect(fuzzySearchArray[0]).toBe('build-linux/opt'); }); }); @@ -91,8 +621,6 @@ describe('FuzzyJobFinder', () => { await fireEvent.change(inputElement, { target: { value: 'debug$' } }); expect(inputElement.value).toBe('debug$'); - await fireEvent.keyDown(inputElement, { key: 'Enter', code: 'Enter' }); - await waitFor(() => { expect(queryAllByTestId('fuzzyList')).toHaveLength(16); const fuzzySearchArray = queryAllByTestId('fuzzyList').map( @@ -102,6 +630,24 @@ describe('FuzzyJobFinder', () => { expect.arrayContaining(searchDebugResults), ); }); + + fireEvent.change(inputElement, { + target: { value: "^build- 'linux | 'android debug$ !asan !pgo" }, + }); + + await waitFor(() => { + const names = queryAllByTestId('fuzzyList').map((job) => job.textContent); + expect(names).toEqual( + expect.arrayContaining([ + 'build-linux/debug', + 'build-android-aarch64/debug', + ]), + ); + expect( + names.every((name) => /^build-.*(?:linux|android).*debug$/.test(name)), + ).toBe(true); + expect(names.every((name) => !/asan|pgo/.test(name))).toBe(true); + }); }); test('Toggling "Use full job list" switches the source list and keeps the search applied', async () => { @@ -138,8 +684,6 @@ describe('FuzzyJobFinder', () => { // Apply a search term; only the linux job in the filtered list matches. const inputElement = getByTitle('Filter the list of runnable jobs'); await fireEvent.change(inputElement, { target: { value: 'linux' } }); - await fireEvent.keyDown(inputElement, { key: 'Enter', code: 'Enter' }); - await waitFor(() => { const names = queryAllByTestId('fuzzyList').map((job) => job.innerHTML); expect(names).toEqual(['test-linux64/opt']); @@ -147,7 +691,7 @@ describe('FuzzyJobFinder', () => { // Toggle to the full list: the source switches AND the search term stays // applied, so we should now see every linux job from the full list. - const checkbox = getByRole('checkbox'); + const checkbox = getByRole('checkbox', { name: 'Use full job list' }); await fireEvent.click(checkbox); await waitFor(() => { @@ -164,6 +708,140 @@ describe('FuzzyJobFinder', () => { }); }); + test('Fast typing only makes the latest results available to add', async () => { + const { getByTitle, getByRole, queryAllByTestId } = + render(testFuzzyJobFinder); + const input = getByTitle('Filter the list of runnable jobs'); + const addAll = getByRole('button', { name: 'Add all' }); + + fireEvent.change(input, { target: { value: 'linux' } }); + fireEvent.change(input, { target: { value: '^addon-tps-xpi$' } }); + expect(addAll).toBeDisabled(); + fireEvent.click(addAll); + expect( + getByRole('button', { name: 'Trigger (0) Selected Jobs' }), + ).toBeDisabled(); + + await waitFor(() => expect(addAll).toBeEnabled()); + expect(queryAllByTestId('fuzzyList').map((job) => job.textContent)).toEqual( + ['addon-tps-xpi'], + ); + + fireEvent.click(addAll); + expect( + getByRole('button', { name: 'Trigger (1) Selected Jobs' }), + ).toBeEnabled(); + }); + + test('Terminates the search worker on list changes, close, and unmount', () => { + const terminate = jest.spyOn(SearchWorker.prototype, 'terminate'); + try { + const finder = cloneElement(testFuzzyJobFinder, { + jobList: [...fuzzyJobList], + }); + const { getByRole, getByTitle, rerender, unmount } = render(finder); + fireEvent.change(getByTitle('Filter the list of runnable jobs'), { + target: { value: 'linux' }, + }); + + fireEvent.click(getByRole('checkbox', { name: 'Use full job list' })); + expect(terminate).toHaveBeenCalledTimes(1); + + rerender(cloneElement(finder, { isOpen: false })); + expect(terminate).toHaveBeenCalledTimes(2); + + rerender(finder); + unmount(); + expect(terminate).toHaveBeenCalledTimes(3); + } finally { + terminate.mockRestore(); + } + }); + + test('Clears the search and selection when the modal closes', async () => { + const { getByRole, getByTitle, queryByRole, rerender } = + render(testFuzzyJobFinder); + const input = getByTitle('Filter the list of runnable jobs'); + fireEvent.change(input, { target: { value: '^addon-tps-xpi$' } }); + + const job = getByRole('option', { name: 'addon-tps-xpi' }); + job.selected = true; + fireEvent.change(job.closest('select')); + const addSelected = getByRole('button', { name: 'Add selected' }); + await waitFor(() => expect(addSelected).toBeEnabled()); + + rerender(cloneElement(testFuzzyJobFinder, { isOpen: false })); + await waitFor(() => expect(queryByRole('dialog')).not.toBeInTheDocument()); + rerender(testFuzzyJobFinder); + + expect(getByTitle('Filter the list of runnable jobs')).toHaveValue(''); + expect(getByRole('option', { name: 'addon-tps-xpi' }).selected).toBe(false); + expect(getByRole('button', { name: 'Add selected' })).toBeDisabled(); + }); + + test.each(['initialization', 'execution'])( + 'Shows an error when the search worker fails during %s', + (phase) => { + let worker; + global.Worker = class extends SearchWorker { + constructor() { + if (phase === 'initialization') throw new Error('Worker unavailable'); + super(); + worker = this; + } + }; + const { getByRole, getByTitle, queryByRole } = render(testFuzzyJobFinder); + expect(queryByRole('alert')).not.toBeInTheDocument(); + + fireEvent.change(getByTitle('Filter the list of runnable jobs'), { + target: { value: 'linux' }, + }); + if (worker) { + act(() => worker.onerror(new ErrorEvent('error'))); + } + + expect(getByRole('alert')).toHaveTextContent( + 'Unable to search runnable jobs.', + ); + expect(document.getElementById('addJobsGroup')).toHaveAttribute( + 'aria-busy', + 'false', + ); + expect(getByRole('button', { name: 'Add all' })).toBeDisabled(); + }, + ); + + test('Keeps the results list enabled and retains selections that still match', async () => { + const { getByTitle, getByRole } = render(testFuzzyJobFinder); + const input = getByTitle('Filter the list of runnable jobs'); + const list = document.querySelector('#addJobsGroup select'); + const addSelected = getByRole('button', { name: 'Add selected' }); + + const job = getByRole('option', { name: 'addon-tps-xpi' }); + job.selected = true; + fireEvent.change(list); + + fireEvent.change(input, { target: { value: '^addon-tps-xpi$' } }); + expect(list).toBeEnabled(); + expect(job.selected).toBe(true); + expect(addSelected).toBeDisabled(); + fireEvent.click(addSelected); + expect( + getByRole('button', { name: 'Trigger (0) Selected Jobs' }), + ).toBeDisabled(); + + await waitFor(() => expect(list.options).toHaveLength(1)); + expect(job.selected).toBe(true); + expect(addSelected).toBeEnabled(); + + fireEvent.change(input, { target: { value: 'linux' } }); + await waitFor(() => expect(list.options).toHaveLength(26)); + expect(addSelected).toBeDisabled(); + + fireEvent.change(input, { target: { value: '' } }); + expect(getByRole('option', { name: 'addon-tps-xpi' }).selected).toBe(false); + }); + test('Selecting a job marks it and moves it to the Selected Jobs list', async () => { const { getByText, queryAllByTestId } = await render(testFuzzyJobFinder); diff --git a/tests/ui/job-view/runnableJobMetadata.worker_test.js b/tests/ui/job-view/runnableJobMetadata.worker_test.js new file mode 100644 index 00000000000..e2cf5348b33 --- /dev/null +++ b/tests/ui/job-view/runnableJobMetadata.worker_test.js @@ -0,0 +1,67 @@ +describe('runnable job metadata worker', () => { + const artifact = 'https://taskcluster.example.com/full-task-graph.json'; + const originalOnMessage = self.onmessage; + const originalFetch = global.fetch; + const originalWorkerGlobalScope = global.WorkerGlobalScope; + + beforeEach(async () => { + global.WorkerGlobalScope = class WorkerGlobalScope {}; + global.fetch = jest.fn(); + jest.spyOn(self, 'postMessage').mockImplementation(() => {}); + await jest.isolateModulesAsync(async () => { + await import('../../../ui/job-view/pushes/runnableJobMetadata.worker'); + }); + }); + + afterEach(() => { + jest.restoreAllMocks(); + self.onmessage = originalOnMessage; + global.fetch = originalFetch; + global.WorkerGlobalScope = originalWorkerGlobalScope; + }); + + test('fetches the graph and projects metadata, including legacy chunk counts', async () => { + const label = 'test-linux64/opt-mochitest-media-2'; + const unchunked = 'test-linux64/opt-single-task-2'; + global.fetch.mockResolvedValue({ + ok: true, + json: async () => ({ + [label]: { task: { extra: { treeherder: { tier: 1 }, chunks: 4 } } }, + [unchunked]: { + task: { extra: { treeherder: { tier: 1 }, chunks: { total: 1 } } }, + }, + 'not-indexed-in-treeherder': { task: {} }, + }), + }); + + await self.onmessage({ data: artifact }); + + expect(global.fetch).toHaveBeenCalledWith(artifact); + expect(self.postMessage).toHaveBeenCalledWith({ + metadata: { + [label]: { + tier: 1, + chunkPattern: 'test-linux64/opt-mochitest-media-*/4', + specialized: false, + buildDependency: undefined, + }, + [unchunked]: { + tier: 1, + chunkPattern: unchunked, + specialized: false, + buildDependency: undefined, + }, + }, + }); + }); + + test('reports a missing graph artifact to the picker', async () => { + global.fetch.mockResolvedValue({ ok: false, status: 404 }); + + await self.onmessage({ data: artifact }); + + expect(self.postMessage).toHaveBeenCalledWith({ + error: 'Task graph returned 404', + }); + }); +}); diff --git a/tests/ui/job-view/runnableJobSearch.worker_test.js b/tests/ui/job-view/runnableJobSearch.worker_test.js new file mode 100644 index 00000000000..d0499b1ae70 --- /dev/null +++ b/tests/ui/job-view/runnableJobSearch.worker_test.js @@ -0,0 +1,29 @@ +test('The worker entry point posts matching indices and transfers their buffer', async () => { + const originalOnMessage = self.onmessage; + const postMessage = jest + .spyOn(self, 'postMessage') + .mockImplementation(() => {}); + global.WorkerGlobalScope = class WorkerGlobalScope {}; + + try { + await jest.isolateModulesAsync(async () => { + await import('../../../ui/job-view/pushes/runnableJobSearch.worker'); + }); + + self.onmessage({ + data: [{ name: 'test-linux64/opt' }, { name: 'asan' }, { name: 'build' }], + }); + expect(postMessage).not.toHaveBeenCalled(); + + self.onmessage({ data: '!asan' }); + expect(postMessage).toHaveBeenCalledTimes(1); + const [[result, transfer]] = postMessage.mock.calls; + expect(result).toEqual({ query: '!asan', indices: Uint32Array.of(0, 2) }); + expect(transfer).toHaveLength(1); + expect(transfer[0]).toBe(result.indices.buffer); + } finally { + postMessage.mockRestore(); + self.onmessage = originalOnMessage; + delete global.WorkerGlobalScope; + } +}); diff --git a/ui/job-view/pushes/FuzzyJobFinder.jsx b/ui/job-view/pushes/FuzzyJobFinder.jsx index 9eb97980305..f7242a1e21e 100644 --- a/ui/job-view/pushes/FuzzyJobFinder.jsx +++ b/ui/job-view/pushes/FuzzyJobFinder.jsx @@ -1,4 +1,4 @@ -import { useState, useCallback, useMemo } from 'react'; +import { useState, useCallback, useEffect, useMemo, useId } from 'react'; import PropTypes from 'prop-types'; import { Button, @@ -10,21 +10,14 @@ import { ModalFooter, InputGroup, } from 'react-bootstrap'; -import Fuse from 'fuse.js'; import PushModel from '../../models/push'; import { formatTaskclusterError } from '../../helpers/errorMessage'; import { sortAlphaNum } from '../../helpers/sort'; import { notify } from '../../shared/stores/notificationStore'; -const FUSE_OPTIONS = { - // http://fusejs.io/ describes the options available - useExtendedSearch: true, - keys: ['name', 'symbol'], - threshold: 0.4, // This seems like a good threshold to remove most false matches, lower is stricter - matchAllTokens: true, - tokenize: true, -}; +import { normalizeTestPaths, planPathJobs } from './runnableJobPaths'; +import useRunnableJobSearch from './useRunnableJobSearch'; // Cap how many nodes we actually render. On firefox repos the // runnable list can be tens of thousands of jobs; mounting (and later tearing @@ -32,49 +25,107 @@ const FUSE_OPTIONS = { // slice keeps the modal responsive; the header still shows the true match // count, and narrowing the search brings the real matches under the cap. const MAX_RENDERED_JOBS = 500; +const EMPTY_JOBS = []; function FuzzyJobFinder({ className, isOpen, toggle, - jobList = [], - filteredJobList = [], + jobList = EMPTY_JOBS, + filteredJobList = EMPTY_JOBS, + pushJobs = EMPTY_JOBS, + loadPickerMetadata, + isLoadingPickerMetadata = false, decisionTaskId = '', + revision = '', currentRepo, }) { const [fuzzySearch, setFuzzySearch] = useState(''); const [selectedList, setSelectedList] = useState([]); const [removeDisabled, setRemoveDisabled] = useState(true); - const [addDisabled, setAddDisabled] = useState(true); const [submitDisabled, setSubmitDisabled] = useState(false); const [useFullList, setUseFullList] = useState(false); + const [showChunkNumbers, setShowChunkNumbers] = useState(false); + const [showSpecialized, setShowSpecialized] = useState(false); + const [existingBuildsOnly, setExistingBuildsOnly] = useState(false); const [addJobsSelected, setAddJobsSelected] = useState([]); const [removeJobsSelected, setRemoveJobsSelected] = useState([]); + const [pathInput, setPathInput] = useState(''); + const controlId = useId(); + const pathMode = Boolean(pathInput.trim()); + + const jobsByLabel = useMemo( + () => new Map(jobList.map((job) => [job.name, job])), + [jobList], + ); + const hasPathMetadata = revision && jobList.some((job) => job.pathScope); + const { pathError, pathJobs, unmatchedPaths } = useMemo(() => { + if (!pathMode) return {}; + const { paths, error } = normalizeTestPaths(pathInput); + if (error) return { pathError: error }; + const { plan, unmatched } = planPathJobs( + selectedList.map((label) => jobsByLabel.get(label)), + paths, + ); + return { pathJobs: plan, unmatchedPaths: unmatched }; + }, [jobsByLabel, pathInput, pathMode, selectedList]); // By default we show a trimmed down list of runnable jobs, but there's an // option to show the full list. - const currentList = useFullList ? jobList : filteredJobList; - - // Build the Fuse index only when the underlying list changes, instead of - // rebuilding it from scratch on every search (expensive with tens of - // thousands of runnable tasks). - const fuse = useMemo(() => new Fuse(currentList, FUSE_OPTIONS), [currentList]); + const availableJobs = useFullList ? jobList : filteredJobList; + const hasBuildMetadata = jobList.some((job) => job.buildDependency); + const hasChunkMetadata = jobList.some( + (job) => job.chunkPattern && job.chunkPattern !== job.name, + ); + const hasSpecializedMetadata = jobList.some( + (job) => job.specialized || Number(job.tier) > 1, + ); + const existingBuilds = useMemo( + () => + new Set( + pushJobs + .filter( + (job) => + ['pending', 'running'].includes(job.state) || + job.result === 'success', + ) + .map((job) => job.job_type_name), + ), + [pushJobs], + ); + const buildFilter = existingBuildsOnly ? existingBuilds : null; + const currentList = useMemo(() => { + const groups = new Map(); + for (const job of availableJobs) { + if (pathMode && !job.pathScope) continue; + if (!showSpecialized && (job.specialized || Number(job.tier) > 1)) + continue; + if (buildFilter && !buildFilter.has(job.buildDependency)) continue; + const name = (!showChunkNumbers && job.chunkPattern) || job.name; + if (!groups.has(name)) { + groups.set(name, { ...job, name, labels: [], symbolAliases: [] }); + } + const group = groups.get(name); + group.labels.push(job.name); + if (job.symbol) { + group.symbolAliases.push(job.symbol); + if (job.groupsymbol && job.groupsymbol !== '?') { + group.symbolAliases.push(`${job.groupsymbol}(${job.symbol})`); + } + } + } + return [...groups.values()]; + }, [availableJobs, buildFilter, pathMode, showChunkNumbers, showSpecialized]); + const matchesByName = useMemo( + () => new Map(currentList.map((job) => [job.name, job.labels])), + [currentList], + ); - /* - * The list of runnable jobs to display, derived from the current search term. - * Filtering only happens when `enter` is pressed (which updates `fuzzySearch`) - * rather than on every keystroke, as the fuzzy search is costly over large - * lists. When the search is empty we fall back to the full (filtered) list of - * runnable jobs. Memoized so the search + sort only reruns when the term or - * source list changes, not on every re-render (e.g. selecting an option). - */ - const fuzzyList = useMemo(() => { - const matches = fuzzySearch - ? fuse.search(fuzzySearch).map((job) => job.item) - : currentList; - // Sort a copy. - return [...matches].sort(sortAlphaNum); - }, [fuse, fuzzySearch, currentList]); + const { + matches: fuzzyList, + pending, + failed, + } = useRunnableJobSearch(currentList, fuzzySearch, isOpen); // Only the first slice is turned into DOM nodes (see MAX_RENDERED_JOBS). const visibleJobs = useMemo( @@ -82,6 +133,21 @@ function FuzzyJobFinder({ [fuzzyList], ); + const visibleSelection = useMemo(() => { + if (addJobsSelected.length === 0) return addJobsSelected; + const visibleNames = new Set(visibleJobs.map((job) => job.name)); + const remaining = addJobsSelected.filter((name) => visibleNames.has(name)); + return remaining.length === addJobsSelected.length + ? addJobsSelected + : remaining; + }, [addJobsSelected, visibleJobs]); + + useEffect(() => { + if (visibleSelection !== addJobsSelected) { + setAddJobsSelected(visibleSelection); + } + }, [addJobsSelected, visibleSelection]); + const selectedSet = useMemo(() => new Set(selectedList), [selectedList]); const sortedSelectedList = useMemo( () => [...selectedList].sort(sortAlphaNum), @@ -89,9 +155,7 @@ function FuzzyJobFinder({ ); const filterJobs = useCallback((ev) => { - if (ev && ev.type === 'keydown' && ev.key === 'Enter') { - setFuzzySearch(ev.target.value); - } + setFuzzySearch(ev.target.value); }, []); const resetForm = useCallback(() => { @@ -100,28 +164,38 @@ function FuzzyJobFinder({ setSubmitDisabled(false); setFuzzySearch(''); setUseFullList(false); + setShowChunkNumbers(false); + setShowSpecialized(false); + setExistingBuildsOnly(false); + setPathInput(''); + setRemoveJobsSelected([]); + setAddJobsSelected([]); }, []); const addAllJobs = useCallback(() => { - const selectedOptions = Array.from(fuzzyList, (option) => option.name); + if (pending || submitDisabled) return; + const selectedOptions = fuzzyList.flatMap((option) => option.labels); // When adding jobs, add only new, unique job names to avoid duplicates setSelectedList((prev) => [...new Set([...prev, ...selectedOptions])]); - }, [fuzzyList]); + }, [fuzzyList, pending, submitDisabled]); const removeAllJobs = useCallback(() => { setSelectedList([]); setRemoveDisabled(true); }, []); - const addJobs = useCallback( - (evt) => { - // When adding jobs, add only new, unique job names to avoid duplicates - setSelectedList((prev) => [...new Set([...prev, ...addJobsSelected])]); - evt.target.parentNode.previousElementSibling.selectedIndex = -1; - }, - [addJobsSelected], - ); + const addJobs = useCallback(() => { + if (pending || submitDisabled) return; + // When adding jobs, add only new, unique job names to avoid duplicates + setSelectedList((prev) => [ + ...new Set([ + ...prev, + ...visibleSelection.flatMap((name) => matchesByName.get(name) ?? []), + ]), + ]); + setAddJobsSelected([]); + }, [matchesByName, pending, submitDisabled, visibleSelection]); const removeJobs = useCallback(() => { setSelectedList((prev) => @@ -130,38 +204,74 @@ function FuzzyJobFinder({ setRemoveDisabled(true); }, [removeJobsSelected]); - const submitJobs = useCallback(() => { - if (selectedList.length > 0) { - notify('Submitting selected jobs...'); - setSubmitDisabled(true); - PushModel.triggerNewJobs(selectedList, decisionTaskId, currentRepo) - .then((result) => { - notify(result, 'success'); - toggle(); - }) - .catch((e) => { - notify(formatTaskclusterError(e), 'danger', { sticky: true }); + const canSubmit = + !submitDisabled && + selectedList.length > 0 && + (!pathMode || (pathJobs?.length > 0 && !unmatchedPaths.length)); + + const submitJobs = useCallback(async () => { + if (!canSubmit) return; + notify('Submitting selected jobs...'); + setSubmitDisabled(true); + try { + if (pathMode) { + const { failed, submitted } = await PushModel.triggerJobsForPaths( + pathJobs, + decisionTaskId, + currentRepo, + revision, + ); + if (failed.length) { + const failedLabels = new Set(failed.map((job) => job.label)); + const retryPaths = new Set( + pathJobs + .filter((job) => failedLabels.has(job.label)) + .flatMap((job) => job.requestedPaths), + ); + setSelectedList([...failedLabels]); + setPathInput([...retryPaths].join('\n')); + notify( + `Requested ${submitted.length} of ${pathJobs.length} path-scoped jobs. ${formatTaskclusterError(failed[0].error)}`, + 'danger', + { sticky: true }, + ); setSubmitDisabled(false); - }); - } else { - notify('Please select at least one job from the list', 'danger'); + return; + } + notify(`Requested ${submitted.length} path-scoped jobs.`, 'success'); + } else { + const result = await PushModel.triggerNewJobs( + selectedList, + decisionTaskId, + currentRepo, + ); + notify(result, 'success'); + } + toggle(); + } catch (error) { + notify(formatTaskclusterError(error), 'danger', { sticky: true }); + setSubmitDisabled(false); } - }, [selectedList, decisionTaskId, currentRepo, notify, toggle]); + }, [ + canSubmit, + pathMode, + pathJobs, + decisionTaskId, + currentRepo, + revision, + selectedList, + toggle, + ]); const toggleFullList = useCallback((evt) => { - // `currentList` (and therefore `fuzzyList`) derives from this state, so the - // list re-derives automatically with the current search term applied. setUseFullList(evt.target.checked); + setAddJobsSelected([]); }, []); const updateAddButton = useCallback((evt) => { - const selectedOptions = Array.from( - evt.target.selectedOptions, - (option) => option.textContent, + setAddJobsSelected( + Array.from(evt.target.selectedOptions, (option) => option.value), ); - - setAddDisabled(selectedOptions.length === 0); - setAddJobsSelected(selectedOptions); }, []); const updateRemoveButton = useCallback((evt) => { @@ -179,7 +289,7 @@ function FuzzyJobFinder({ onExited={resetForm} size="lg" show={isOpen} - onHide={toggle} + onHide={submitDisabled ? undefined : toggle} className={className} > Add New Jobs (Search) @@ -188,8 +298,9 @@ function FuzzyJobFinder({ @@ -197,20 +308,108 @@ function FuzzyJobFinder({ + + {hasChunkMetadata && ( + { + setShowChunkNumbers(event.target.checked); + setAddJobsSelected([]); + }} + /> + )} + {hasSpecializedMetadata && ( + setShowSpecialized(event.target.checked)} + /> + )} + {hasBuildMetadata && ( + { + setExistingBuildsOnly(event.target.checked); + if (event.target.checked) { + setSelectedList((prev) => + prev.filter((label) => + existingBuilds.has( + jobsByLabel.get(label)?.buildDependency, + ), + ), + ); + } + }} + /> + )} + + {loadPickerMetadata && ( + + {isLoadingPickerMetadata + ? 'Loading job filters and test paths…' + : 'Load job filters and test paths'} + + )} + {hasPathMetadata && ( + + Test paths + { + const value = event.target.value; + setPathInput(value); + if (value.trim()) { + setSelectedList((prev) => + prev.filter((label) => jobsByLabel.get(label)?.pathScope), + ); + } + }} + /> + + )} Runnable Jobs [{fuzzyList.length}] - + Add selected - + Add all @@ -220,14 +419,28 @@ function FuzzyJobFinder({ Refine your search to narrow the list. )} - - + {failed && Unable to search runnable jobs.} + + {visibleJobs.map((e) => ( 1 + ? `${e.name} (${e.labels.length} chunks)` + : `${e.name} - ${e.groupsymbol}(${e.symbol})` + } key={e.name} - className={selectedSet.has(e.name) ? 'selected' : ''} + className={ + e.labels.every((label) => selectedSet.has(label)) + ? 'selected' + : '' + } > {e.name} @@ -240,7 +453,7 @@ function FuzzyJobFinder({ Remove selected @@ -248,7 +461,7 @@ function FuzzyJobFinder({ Remove all @@ -262,16 +475,37 @@ function FuzzyJobFinder({ ))} + {pathError && {pathError}} + {selectedList.length > 0 && unmatchedPaths?.length > 0 && ( + + No selected test groups match {unmatchedPaths.join(', ')}. + + )} + {pathJobs?.length > 0 && ( + + + {pathJobs.length === 1 + ? '1 task matches the test paths' + : `${pathJobs.length} tasks match the test paths`} + + + {pathJobs.slice(0, MAX_RENDERED_JOBS).map(({ label }) => ( + {label} + ))} + + + )} + + Trigger ({pathMode ? (pathJobs?.length ?? 0) : selectedList.length}) + Selected Jobs + {' '} - Trigger ({selectedList.length}) Selected Jobs - {' '} - Cancel @@ -285,8 +519,12 @@ FuzzyJobFinder.propTypes = { isOpen: PropTypes.bool.isRequired, toggle: PropTypes.func.isRequired, decisionTaskId: PropTypes.string, + revision: PropTypes.string, jobList: PropTypes.arrayOf(PropTypes.shape({})), filteredJobList: PropTypes.arrayOf(PropTypes.shape({})), + pushJobs: PropTypes.arrayOf(PropTypes.shape({})), + loadPickerMetadata: PropTypes.func, + isLoadingPickerMetadata: PropTypes.bool, currentRepo: PropTypes.shape({}).isRequired, }; diff --git a/ui/job-view/pushes/Push.jsx b/ui/job-view/pushes/Push.jsx index 574f1dcb767..15268fdda25 100644 --- a/ui/job-view/pushes/Push.jsx +++ b/ui/job-view/pushes/Push.jsx @@ -12,6 +12,7 @@ import { thTryRepos, } from '../../helpers/constants'; import decompress from '../../helpers/gzip'; +import { getArtifactsUrl } from '../../helpers/url'; import { getAllUrlParams, getUrlParam, @@ -97,6 +98,45 @@ const fetchGeckoDecisionArtifact = async (project, revision, filePath) => { return artifactContents; }; +const excludedJobNames = new RegExp( + ` + (balrog|beetmover|bouncer-locations-firefox|build-docker-image|build-(.+)-nightly| + build-(.+)-upload-symbols|checksums|cron-bouncer|dmd|fetch|google-play-strings| + push-to-release|mar-signing|nightly|packages|release-bouncer|release-early| + release-final|release-secondary|release-snap|release-source|release-update| + repackage-l10n|repo-update|searchfox|sign-and-push|test-(.+)-devedition| + test-linux(32|64)(-asan|-pgo|-qr)?/(opt|debug)-jittest|test-macosx64-ccov| + test-verify|test-windows10-64-ux|toolchain|upload-generated-sources)`.replace( + /\s/g, + '', + ), +); + +function fetchRunnableJobMetadata(decisionTask, rootUrl) { + return new Promise((resolve, reject) => { + const worker = new Worker( + new URL('./runnableJobMetadata.worker.js', import.meta.url), + ); + worker.onmessage = ({ data }) => { + worker.terminate(); + if (data.error) reject(new Error(data.error)); + else resolve(data.metadata); + }; + worker.onerror = (event) => { + worker.terminate(); + reject(new Error(event.message)); + }; + worker.postMessage( + getArtifactsUrl({ + taskId: decisionTask.id, + run: decisionTask.run, + rootUrl, + artifactPath: 'public/full-task-graph.json', + }), + ); + }); +} + function Push({ push, currentRepo, @@ -128,7 +168,7 @@ function Push({ const [collapsed, setCollapsed] = useState(collapsedPushes.includes(push.id)); const [filteredTryPush, setFilteredTryPush] = useState(false); const [fuzzyJobList, setFuzzyJobList] = useState([]); - const [filteredFuzzyList, setFilteredFuzzyList] = useState([]); + const [pickerMetadata, setPickerMetadata] = useState(null); const [manifestsByTask, setManifestsByTask] = useState({}); const containerRef = useRef(null); @@ -480,39 +520,57 @@ function Push({ mapPushJobs(newJobList); }, [mapPushJobs]); - const showFuzzyJobs = useCallback(async () => { - const createRegExp = (str, opts) => - new RegExp(str.raw[0].replace(/\s/gm, ''), opts || ''); - const excludedJobNames = createRegExp` - (balrog|beetmover|bouncer-locations-firefox|build-docker-image|build-(.+)-nightly| - build-(.+)-upload-symbols|checksums|cron-bouncer|dmd|fetch|google-play-strings| - push-to-release|mar-signing|nightly|packages|release-bouncer|release-early| - release-final|release-secondary|release-snap|release-source|release-update| - repackage-l10n|repo-update|searchfox|sign-and-push|test-(.+)-devedition| - test-linux(32|64)(-asan|-pgo|-qr)?\/(opt|debug)-jittest|test-macosx64-ccov| - test-verify|test-windows10-64-ux|toolchain|upload-generated-sources)`; + const decisionTask = decisionTaskMap[push.id]; + const rootUrl = currentRepo.tc_root_url; + const metadataKey = decisionTask?.id + ? `${rootUrl}/${decisionTask.id}/${decisionTask.run}` + : null; + const activeMetadata = + pickerMetadata?.key === metadataKey ? pickerMetadata : null; + const metadata = activeMetadata?.jobs; + const enrichedFuzzyList = useMemo( + () => + metadata + ? fuzzyJobList.map((job) => ({ ...job, ...metadata[job.name] })) + : fuzzyJobList, + [fuzzyJobList, metadata], + ); + const filteredFuzzyList = useMemo( + () => enrichedFuzzyList.filter((job) => !excludedJobNames.test(job.name)), + [enrichedFuzzyList], + ); + + const loadPickerMetadata = async () => { + if (!metadataKey || activeMetadata) return; + const request = { key: metadataKey, pending: true }; + setPickerMetadata(request); + try { + const jobs = await fetchRunnableJobMetadata(decisionTask, rootUrl); + setPickerMetadata((current) => + current === request ? { key: metadataKey, jobs } : current, + ); + } catch { + setPickerMetadata((current) => (current === request ? null : current)); + notify('Job filters and test paths are unavailable for this push.'); + } + }; + + const showFuzzyJobs = useCallback(async () => { try { notify('Fetching runnable jobs... This could take a while...'); - let fuzzyList = await RunnableJobModel.getList(currentRepo, { - decisionTask: decisionTaskMap[push.id], + const runnableJobs = await RunnableJobModel.getList(currentRepo, { + decisionTask, }); - fuzzyList = [ - ...new Set( - fuzzyList.map((job) => { - const obj = {}; - obj.name = job.job_type_name; - obj.symbol = job.job_type_symbol; - obj.groupsymbol = job.job_group_symbol; - return obj; - }), - ), - ].sort((a, b) => (a.name > b.name ? 1 : -1)); - const filteredList = fuzzyList.filter( - (job) => job.name.search(excludedJobNames) < 0, + setFuzzyJobList( + runnableJobs + .map((job) => ({ + name: job.job_type_name, + symbol: job.job_type_symbol, + groupsymbol: job.job_group_symbol, + })) + .sort((a, b) => (a.name > b.name ? 1 : -1)), ); - setFuzzyJobList(fuzzyList); - setFilteredFuzzyList(filteredList); setFuzzyModal(true); } catch (error) { notify( @@ -520,7 +578,7 @@ function Push({ 'danger', ); } - }, [currentRepo, decisionTaskMap, push.id]); + }, [currentRepo, decisionTask]); const cycleWatchState = useCallback(async () => { if (!notificationSupported) { @@ -609,7 +667,6 @@ function Push({ branch, } = push; const tipRevision = push.revisions[0]; - const decisionTask = decisionTaskMap[push.id]; const decisionTaskId = decisionTask ? decisionTask.id : null; if (isOnlyRevision) { @@ -631,8 +688,14 @@ function Push({ 1) + return label.replace(/-\d+$/, `-*/${chunks}`); + return chunks?.total > 1 ? label.replace(/-\d+$/, '-*') : label; +} + +export function getPickerMetadata(graph) { + return Object.fromEntries( + Object.entries(graph).flatMap(([label, node]) => { + const { attributes = {}, dependencies = {}, kind, task } = node; + const extra = task?.extra; + const treeherder = extra?.treeherder; + if (!treeherder) return []; + + const suite = attributes.unittest_suite; + const chunks = extra.chunks; + const isConfirmFailure = label.endsWith('-cf'); + const buildSettings = extra['test-setting']?.build; + const specialized = + instrumentedBuild.test(dependencies.build ?? label) || + Boolean( + buildSettings?.asan || buildSettings?.tsan || buildSettings?.ccov, + ) || + Boolean(attributes['duplicate-of']) || + Boolean(attributes.unittest_variant) || + isConfirmFailure || + kind === 'browsertime' || + kind === 'perftest' || + suite === 'talos'; + + const metadata = { + tier: treeherder.tier, + chunkPattern: isConfirmFailure ? label : chunkPattern(label, chunks), + specialized, + buildDependency: dependencies.build, + }; + // Gecko's decision task does not resolve per-chunk manifests for + // reftest-qr and crashtest-qr. This picker needs those mappings to + // choose chunks from an existing graph, as opposed to recomputing them. + if ( + pathSuites.test(suite ?? '') && + !isConfirmFailure && + !['reftest-qr', 'crashtest-qr'].includes(suite) && + Array.isArray(attributes.test_manifests) && + attributes.test_manifests.length && + task.payload?.env?.MOZHARNESS_TEST_PATHS + ) { + metadata.pathScope = { suite, manifests: attributes.test_manifests }; + } + + return [[label, metadata]]; + }), + ); +} + +if (typeof WorkerGlobalScope !== 'undefined') { + self.onmessage = async ({ data: url }) => { + try { + const response = await fetch(url); + if (!response.ok) + throw new Error(`Task graph returned ${response.status}`); + self.postMessage({ metadata: getPickerMetadata(await response.json()) }); + } catch (error) { + self.postMessage({ error: error.message }); + } + }; +} diff --git a/ui/job-view/pushes/runnableJobPaths.js b/ui/job-view/pushes/runnableJobPaths.js new file mode 100644 index 00000000000..368bc4c977f --- /dev/null +++ b/ui/job-view/pushes/runnableJobPaths.js @@ -0,0 +1,70 @@ +function includesPath(directory, path) { + return directory === path || path.startsWith(`${directory}/`); +} + +export function normalizeTestPaths(input) { + const paths = new Set(); + for (const line of input.split(/\r?\n/)) { + const path = line.trim().replace(/\/+$/, '').replace(/^\.\//, ''); + if (!line.trim()) continue; + if ( + !path || + path.startsWith('/') || + path.startsWith('-') || + path.split('/').some((part) => part === '..' || part === '.') || + /[:\\]/.test(path) + ) { + return { error: `Expected a repository-relative test path: ${line}` }; + } + paths.add(path); + } + return { paths: [...paths] }; +} + +function sourcePath(manifest) { + if (manifest.startsWith('/_mozilla/')) { + return `testing/web-platform/mozilla/tests/${manifest.slice('/_mozilla/'.length)}`; + } + if (manifest.startsWith('/')) { + return `testing/web-platform/tests${manifest}`; + } + return manifest; +} + +export function planPathJobs(jobs, paths) { + const matched = new Set(); + const plan = []; + for (const job of jobs) { + if (!job?.pathScope) continue; + const { suite, manifests } = job.pathScope; + const scope = new Set(); + const requestedPaths = new Set(); + for (const manifest of manifests) { + const source = sourcePath(manifest); + for (const path of paths) { + if (includesPath(path, source)) { + scope.add(manifest); + } else if ( + suite.startsWith('web-platform-tests') && + includesPath(source, path) + ) { + scope.add(path); + } else { + continue; + } + matched.add(path); + requestedPaths.add(path); + } + } + if (scope.size) { + plan.push({ + label: job.name, + suite, + symbol: job.symbol, + paths: [...scope], + requestedPaths: [...requestedPaths], + }); + } + } + return { plan, unmatched: paths.filter((path) => !matched.has(path)) }; +} diff --git a/ui/job-view/pushes/runnableJobSearch.worker.js b/ui/job-view/pushes/runnableJobSearch.worker.js new file mode 100644 index 00000000000..916a0a06317 --- /dev/null +++ b/ui/job-view/pushes/runnableJobSearch.worker.js @@ -0,0 +1,55 @@ +import { byLengthAsc, extendedMatch, Fzf } from 'fzf'; + +export function createSearchHandler(sendResults) { + let finder; + const symbolIndex = new Map(); + + return ({ data }) => { + if (Array.isArray(data)) { + symbolIndex.clear(); + data.forEach(({ symbol, groupsymbol, symbolAliases }, index) => { + const aliases = symbolAliases ?? [ + symbol, + symbol && + groupsymbol && + groupsymbol !== '?' && + `${groupsymbol}(${symbol})`, + ]; + for (const alias of aliases) { + if (!alias) continue; + const key = alias.toLowerCase(); + if (!symbolIndex.has(key)) symbolIndex.set(key, new Set()); + symbolIndex.get(key).add(index); + } + }); + finder = new Fzf( + data.map(({ name }, index) => ({ name, index })), + { + selector: (job) => job.name, + match: extendedMatch, + tiebreakers: [byLengthAsc], + }, + ); + return; + } + + const matches = finder.find(data); + // A standalone symbol can also match. Keep extended queries on task + // labels so operators and label ranking behave like mach try fuzzy. + const symbolMatches = symbolIndex.get(data.trim().toLowerCase()); + const indices = symbolMatches + ? Uint32Array.from( + new Set([...symbolMatches, ...matches.map(({ item }) => item.index)]), + ) + : Uint32Array.from(matches, ({ item }) => item.index); + // fzf keeps input order when a query only excludes matches. + if (matches[0]?.score === 0 && !symbolMatches) indices.sort(); + sendResults({ query: data, indices }, [indices.buffer]); + }; +} + +if (typeof WorkerGlobalScope !== 'undefined') { + self.onmessage = createSearchHandler((data, transfer) => + self.postMessage(data, transfer), + ); +} diff --git a/ui/job-view/pushes/useRunnableJobSearch.js b/ui/job-view/pushes/useRunnableJobSearch.js new file mode 100644 index 00000000000..3d5c3f39efe --- /dev/null +++ b/ui/job-view/pushes/useRunnableJobSearch.js @@ -0,0 +1,85 @@ +import { useEffect, useMemo, useRef, useState } from 'react'; + +import { sortAlphaNum } from '../../helpers/sort'; + +export default function useRunnableJobSearch(jobs, query, isOpen) { + const search = useRef(null); + const [result, setResult] = useState(null); + const [failedJobs, setFailedJobs] = useState(null); + + useEffect(() => { + setResult(null); + setFailedJobs(null); + if (!isOpen) return; + + let worker; + try { + worker = new Worker( + new URL('./runnableJobSearch.worker.js', import.meta.url), + ); + } catch { + setFailedJobs(jobs); + return; + } + let latestQuery = ''; + let inFlight = false; + + function sendLatestQuery() { + if (!latestQuery.trim()) return; + inFlight = true; + worker.postMessage(latestQuery); + } + + // Keep just one search in flight so intermediate keystrokes cannot build + // up a queue of obsolete searches while the worker is busy. + search.current = (nextQuery) => { + latestQuery = nextQuery; + if (!inFlight) sendLatestQuery(); + }; + worker.onmessage = ({ data }) => { + inFlight = false; + if (data.query === latestQuery) { + setResult({ jobs, ...data }); + } else { + sendLatestQuery(); + } + }; + worker.onerror = () => setFailedJobs(jobs); + worker.postMessage( + jobs.map(({ name, symbol, groupsymbol, symbolAliases }) => ({ + name, + symbol, + groupsymbol, + symbolAliases, + })), + ); + + return () => { + search.current = null; + worker.onmessage = null; + worker.onerror = null; + worker.terminate(); + }; + }, [jobs, isOpen]); + + useEffect(() => { + search.current?.(query); + }, [jobs, query, isOpen]); + + const browseList = useMemo(() => [...jobs].sort(sortAlphaNum), [jobs]); + const currentResult = result?.jobs === jobs ? result : null; + const isSearching = Boolean(query.trim()); + const matches = useMemo( + () => + isSearching && currentResult + ? Array.from(currentResult.indices, (index) => jobs[index]) + : browseList, + [browseList, currentResult, isSearching, jobs], + ); + + return { + matches, + pending: isSearching && currentResult?.query !== query, + failed: isSearching && failedJobs === jobs, + }; +} diff --git a/ui/models/push.js b/ui/models/push.js index 2b0afe220af..f2a6eb0e391 100644 --- a/ui/models/push.js +++ b/ui/models/push.js @@ -27,6 +27,8 @@ const convertDates = function convertDates(locationParams) { return locationParams; }; +const pathActionConcurrency = 4; + export const decisionTaskIdCache = {}; export default class PushModel { @@ -122,6 +124,58 @@ export default class PushModel { ); } + static async triggerJobsForPaths( + plan, + decisionTaskId, + currentRepo, + revision, + ) { + const results = await TaskclusterModel.load( + decisionTaskId, + null, + currentRepo, + ); + const action = getAction(results.actions, 'backfill-task'); + const failed = []; + const submitted = []; + for ( + let offset = 0; + offset < plan.length; + offset += pathActionConcurrency + ) { + const batch = plan.slice(offset, offset + pathActionConcurrency); + const requests = await Promise.allSettled( + batch.map((job) => + TaskclusterModel.submit({ + action, + decisionTaskId, + taskId: null, + task: null, + input: { + label: job.label, + revision, + symbol: job.symbol, + test_manifests: { [job.suite]: job.paths }, + times: 1, + retrigger: true, + }, + staticActionVariables: results.staticActionVariables, + currentRepo, + }), + ), + ); + requests.forEach((request, index) => { + const { label } = batch[index]; + if (request.status === 'fulfilled') { + submitted.push({ label, taskId: request.value }); + } else { + failed.push({ label, error: request.reason }); + } + }); + } + return { failed, submitted }; + } + static getHealth(repoName, revision) { return getData( getProjectUrl(`${pushEndpoint}health/?revision=${revision}`, repoName),