diff --git a/docs/deployments.md b/docs/deployments.md index 1c2428a..1e18b31 100644 --- a/docs/deployments.md +++ b/docs/deployments.md @@ -28,7 +28,13 @@ has no row. Each row carries what Command Center's columns show: - **Branch:** `repositoryName` and `branchName`. - **Date:** `startedAt` (when it was created, until it starts) and `finishedAt`. - **Type:** `kindLabel`, the backend's label. -- **State:** `state`, with `outcome`, `errorCode` and `error`. +- **State:** `state`, with `outcome`, `errorCode` and `error`. A `blocked` deployment's + outcome is usually only `workflow_prerequisite_failed`, so the read asks for each row's + workflow run (`include=workflow_run`) and a blocked row carries `blockedBy`: the workflow + (`workflowRunUid`, `workflowPath`, `workflowState`) and the `steps` that failed, found by + walking back from the deployment's own steps through the steps they need. Command Center + says the same as `migrate failed · 2 blocked`. `deployment-run` and `deployment-wait` + return `blockedBy` too. - **Progress:** `steps` in order. A stage left running in a deployment that ended reads `stopped`. - **Source:** `source`. diff --git a/package-lock.json b/package-lock.json index 39d4702..5f337e9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@dev-mainsequence/devtools", - "version": "0.3.22", + "version": "0.3.23", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@dev-mainsequence/devtools", - "version": "0.3.22", + "version": "0.3.23", "license": "MIT", "bin": { "ms-devtools": "dist/runner.js" diff --git a/package.json b/package.json index a21428e..de2d13e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@dev-mainsequence/devtools", - "version": "0.3.22", + "version": "0.3.23", "description": "Shared MainSequence developer actions, project operations, MCP client and command runner", "license": "MIT", "engines": { diff --git a/src/shared/deployments.ts b/src/shared/deployments.ts index 203ebb1..b8b080a 100644 --- a/src/shared/deployments.ts +++ b/src/shared/deployments.ts @@ -115,13 +115,14 @@ export function deploymentRun(row: unknown, now: number) { const createdAt = when(run.created_at), finishedAt = when(run.finished_at); const startedAt = when(run.started_at) ?? earliest(steps.map(step => step.startedAt)) ?? createdAt; const workflow = run.workflow_run ? workflowRun(run.workflow_run, now) : null; - return { kind: 'deployment_run' as const, uid, state: text(run.state, 40) || 'unknown', outcome: text(run.outcome, 100), operation: text(run.operation, 60), source: text(run.source, 60), + const state = text(run.state, 40) || 'unknown', workflowStepKeys = list(run.workflow_step_keys).slice(0, 40).map(key => text(key, 200)); + return { kind: 'deployment_run' as const, uid, state, outcome: text(run.outcome, 100), operation: text(run.operation, 60), source: text(run.source, 60), targetLabel: text(target.display_name || target.name, 200) || text(run.target_type, 60), targetType: text(run.target_type, 60), repositoryUid: optionalUuid(repository.uid), repositoryName: text(repository.name, 200), branchUid: optionalUuid(run.code_repository_branch_uid) ?? optionalUuid(branch.uid), branchName: text(branch.repository_branch, 200), commit: text(run.commit_sha, 40).slice(0, 7), createdAt, startedAt, finishedAt, durationMs: duration(startedAt, finishedAt, now), currentStepKey: text(rec(run.pipeline).current_step_key, 200), steps, - workflowStepKeys: list(run.workflow_step_keys).slice(0, 40).map(key => text(key, 200)), workflowRun: workflow, + workflowStepKeys, workflowRun: workflow, blockedBy: state === 'blocked' && workflow ? blockedBy(uid, workflowStepKeys, workflow) : null, logsAvailable: rec(run.logs).state === 'available' || typeof rec(run.logs).url === 'string', error: errorText(run.error), errorCode: errorCode(run.error), releaseName: text(release.name, 200) || (RELEASE_TARGETS.has(text(run.target_type, 60)) ? text(target.name, 200) : ''), agentName: text(rec(target.agent).name, 200), targetKind: text(target.kind, 60), targetKindLabel: text(target.kind_label, 100), revisionUid: optionalUuid(rec(target.revision).uid), @@ -129,6 +130,31 @@ export function deploymentRun(row: unknown, now: number) { } type Run = NonNullable>; +/** Workflow step states that keep the steps needing them from running. */ +const FAILED_STEP_STATES = new Set(['failed', 'error', 'errored', 'cancelled', 'canceled', 'stopped', 'timed_out']); +/** Workflow step states of a step that did not run because a step it needs did not succeed. */ +const UNRUN_STEP_STATES = new Set(['blocked', 'skipped', 'superseded']); +/** + * Why the workflow blocked this deployment, as Command Center says it (`migrate failed · 2 blocked`): the workflow + * and the steps that failed. Walks back from this deployment's own steps through the steps they need, past the + * ones that did not run, to the ones that failed. When that leads nowhere, every step that failed is named. + */ +function blockedBy(uid: string, ownKeys: string[], workflow: NonNullable>) { + const byKey = new Map(workflow.steps.map(step => [step.key, step])); + const queue = workflow.steps.filter(step => ownKeys.includes(step.key) || step.deploymentRunUid === uid).map(step => step.key); + const seen = new Set(), causes = new Set(); + for (let key = queue.shift(); key !== undefined; key = queue.shift()) { + const step = byKey.get(key); + if (!step || seen.has(key)) continue; + seen.add(key); + if (FAILED_STEP_STATES.has(step.state)) causes.add(key); + else if (UNRUN_STEP_STATES.has(step.state)) queue.push(...step.needs); + } + const failed = workflow.steps.filter(step => causes.size ? causes.has(step.key) : FAILED_STEP_STATES.has(step.state)); + return { workflowRunUid: workflow.uid, workflowPath: workflow.workflowPath, workflowState: workflow.state, + steps: failed.map(step => ({ key: step.key, state: step.state })) }; +} + function errorCode(value: unknown): string { const code = rec(value).code; return typeof code === 'string' ? text(code, 100) : ''; @@ -140,7 +166,7 @@ function releaseDeployment(run: Run) { kindLabel: run.targetKindLabel || RELEASE_KINDS[run.targetKind] || run.targetKind.replace(/_/g, ' '), revisionUid: run.revisionUid, commit: run.commit, repositoryName: run.repositoryName, branchUid: run.branchUid, branchName: run.branchName, state: run.state, outcome: run.outcome, source: run.source, createdAt: run.createdAt, startedAt: run.startedAt, finishedAt: run.finishedAt, durationMs: active || run.finishedAt ? run.durationMs : null, - error: run.error, errorCode: run.errorCode, + error: run.error, errorCode: run.errorCode, blockedBy: run.blockedBy, // A stage left running in a deployment that has ended was stopped, as Command Center shows it. steps: run.steps.map(step => ({ name: step.name || step.key, state: !active && step.state === 'running' ? 'stopped' : step.state })) }; } @@ -250,7 +276,8 @@ export function createDeployments(options: { host: HostServices; signal?: AbortS if (input.releaseKind !== undefined && !(typeof input.releaseKind === 'string' && Object.hasOwn(RELEASE_KINDS, input.releaseKind))) throw new ToolingError('INVALID_REQUEST', `Choose a release kind: ${Object.keys(RELEASE_KINDS).join(', ')}.`); if (input.search !== undefined && typeof input.search !== 'string') throw new ToolingError('INVALID_REQUEST', 'Search with text.'); const kind = input.releaseKind || '', search = text(input.search ?? '', 300).trim(); - const query = releaseQuery(environmentUid, branchUid, { created_after: new Date(now - days * 86_400_000).toISOString(), limit: String(limit), offset: String(offset) }); + // With its workflow run, a blocked row can name the workflow step that failed. + const query = releaseQuery(environmentUid, branchUid, { created_after: new Date(now - days * 86_400_000).toISOString(), limit: String(limit), offset: String(offset), include: 'workflow_run' }); if (releaseUid) query.set('target_uid', releaseUid); if (kind) query.set('target_kind', kind); if (search) query.set('search', search); @@ -272,7 +299,7 @@ export function createDeployments(options: { host: HostServices; signal?: AbortS const timeout = integer(input.timeoutSeconds, 1, WAIT_LIMIT_SECONDS, 60, `Wait between 1 and ${WAIT_LIMIT_SECONDS} seconds.`); const deadline = now + timeout * 1000; for (let reads = 1; ; reads++) { - const row = await scoped.request(backend, 'GET', `/api/v1/deployment-runs/${runUid}/`); + const row = await scoped.request(backend, 'GET', `/api/v1/deployment-runs/${runUid}/?include=workflow_run`); const read = Date.now(), readAt = new Date(read).toISOString(); if (rec(row).hidden === true) { data = { hidden: true, uid: runUid, now: readAt }; summary = HIDDEN_DEPLOYMENT; break; } const run = deploymentRun(row, read); diff --git a/tests/deployment-release-history.test.cjs b/tests/deployment-release-history.test.cjs index 07428fa..e2c5ae7 100644 --- a/tests/deployment-release-history.test.cjs +++ b/tests/deployment-release-history.test.cjs @@ -5,7 +5,7 @@ const API = id(10), AGENT = id(11), SITE = id(12), JOB = id(13), IMAGE = id(14), const iso = minutes => new Date(Date.parse('2026-11-18T12:00:00Z') + minutes * 60_000).toISOString(); const step = (sequence, name, state, minutes, base = 0) => ({ uid: id(500 + sequence), sequence, name, kind: name.toLowerCase(), state, started_at: iso(base), finished_at: state === 'running' || state === 'pending' ? null : iso(base + minutes) }); -function run(n, release, state, { minutes = 4, error, type = 'resource_release', steps } = {}) { +function run(n, release, state, { minutes = 4, error, type = 'resource_release', steps, workflow, ownSteps = [] } = {}) { return { uid: id(100 + n), target_type: type, target_uid: release, state, operation: 'build_and_deploy', source: 'repository_event', commit_sha: `abc${n}def0123456`, code_repository_branch_uid: BRANCH, created_at: iso(-n * 60), started_at: iso(-n * 60), finished_at: ['queued', 'running'].includes(state) ? null : iso(-n * 60 + minutes), target: { uid: release, name: 'release-name', display_name: 'pricing-api', kind: type === 'resource_release' ? 'fastapi' : type, kind_label: { resource_release: 'FastAPI', harness_agent: 'Harness Agent', static_site: 'Static site', job: 'Job' }[type], @@ -13,8 +13,19 @@ function run(n, release, state, { minutes = 4, error, type = 'resource_release', agent: type === 'harness_agent' ? { uid: id(6), name: 'Risk Analyst' } : null, resource_release: ['resource_release', 'harness_agent'].includes(type) ? { uid: release, name: type === 'harness_agent' ? 'tau' : 'app' } : null }, pipeline: { current_step_key: state === 'running' ? 'deploy' : '', steps: steps || [step(1, 'Build', 'succeeded', 3, -n * 60), step(2, 'Deploy', state === 'succeeded' ? 'succeeded' : state === 'running' ? 'running' : 'failed', minutes, -n * 60)] }, - ...(error ? { error } : {}), billing: { secret: 'never-return' }, cost_summary: { total: 99 } }; + ...(error ? { error } : {}), ...(workflow ? { workflow_run: workflow, workflow_step_keys: ownSteps } : {}), billing: { secret: 'never-return' }, cost_summary: { total: 99 } }; } +/** MetaTables' workflow of 2026-11-23 13:13: migrate failed, so both deployments it would have made were blocked. */ +const WORKFLOW = id(30); +const wfStep = (step_key, operation, state, needs = [], deployment_run_uid = null) => ({ step_key, operation, resource_key: step_key, state, needs, deployment_run_uid, + reason: state === 'blocked' ? 'prerequisite_not_successful' : '', dispatch_authorized_at: iso(-50), dispatch_started_at: null, finished_at: iso(-45), error: null }); +const workflowRun = (steps, state = 'failed') => ({ uid: WORKFLOW, workflow_path: '.mainsequence/workflows/metatables-api.yaml', commit_sha: 'abc1def0123456', state, reason: '', + creation_date: iso(-60), finished_at: iso(-45), steps }); +const METATABLES = workflowRun([wfStep('image', 'prepare_image', 'succeeded', [], id(101)), wfStep('agent_image', 'prepare_image', 'succeeded', [], id(102)), + wfStep('migrate', 'run_job', 'failed', ['image']), wfStep('deploy_api', 'deploy', 'blocked', ['migrate'], id(101)), + wfStep('deploy_agent', 'deploy', 'blocked', ['agent_image', 'deploy_api'], id(102))]); +const blocked = (n, release, type, ownSteps, workflow = METATABLES) => run(n, release, 'blocked', { type, workflow, ownSteps, + steps: [step(1, 'Resolve revision', 'skipped', 0, -n * 60), step(2, 'Deploy runtime', 'skipped', 0, -n * 60)] }); function fixture({ runs, waitStates, ignoreFilters = false } = {}) { const calls = [], state = { username: 'fixture' }; const allRuns = runs || [run(0, API, 'running'), run(1, JOB, 'running', { type: 'job' }), run(2, API, 'succeeded'), run(3, IMAGE, 'succeeded', { type: 'code_repository_image' }), @@ -29,6 +40,8 @@ function fixture({ runs, waitStates, ignoreFilters = false } = {}) { if (!ignoreFilters && q.get('target_type__in')) rows = rows.filter(row => q.get('target_type__in').split(',').includes(row.target_type)); if (q.get('target_uid')) rows = rows.filter(row => row.target_uid === q.get('target_uid')); if (q.get('state__in')) rows = rows.filter(row => q.get('state__in').split(',').includes(row.state)); + // As the backend: the workflow run comes only when asked for. + if (q.get('include') !== 'workflow_run') rows = rows.map(({ workflow_run, workflow_step_keys, ...row }) => row); return Response.json({ count: rows.length, results: rows }); } if (u.pathname === `/api/v1/deployment-runs/${id(100)}/`) { @@ -50,7 +63,7 @@ test('release deployment history is one read of resource release deployments onl assert.deepEqual(calls.map(call => call.path), ['/api/v1/deployment-runs/'], 'no release inventory, revisions, branches or per-release reads'); const { query } = calls[0]; assert.equal(query.target_type__in, 'resource_release,harness_agent,static_site'); - assert.deepEqual([query.organization_environment_uid, query.ordering, query.limit, query.offset], [ENV, '-creation_date', '25', '0']); + assert.deepEqual([query.organization_environment_uid, query.ordering, query.limit, query.offset, query.include], [ENV, '-creation_date', '25', '0', 'workflow_run']); assert.ok(Math.abs(Date.parse(query.created_after) - (Date.now() - 86_400_000)) < 60_000, 'the history opens on the last day'); assert.deepEqual(result.data.results.map(row => row.uid), [id(100), id(102), id(104), id(105)]); assert.equal(result.data.count, 4); assert.equal(result.summary, '4 deployments in the last day.'); @@ -68,6 +81,32 @@ test('each row carries what Command Center\'s columns show', async () => { assert.deepEqual([site.releaseUid, site.releaseName], [SITE, 'release-name'], 'a target without a release reference is still that release'); }); +test('a blocked row names the workflow step that failed, through the steps that did not run', async () => { + const runs = [blocked(1, API, 'resource_release', ['image', 'deploy_api']), blocked(2, AGENT, 'harness_agent', ['agent_image', 'deploy_agent']), run(3, SITE, 'succeeded', { type: 'static_site' })]; + const [api, agent, site] = (await fixture({ runs }).run('deployment-release-history', { environmentUid: ENV })).data.results; + const migrate = { workflowRunUid: WORKFLOW, workflowPath: '.mainsequence/workflows/metatables-api.yaml', workflowState: 'failed', steps: [{ key: 'migrate', state: 'failed' }] }; + assert.deepEqual(api.blockedBy, migrate, 'deploy_api needs migrate'); + assert.deepEqual(agent.blockedBy, migrate, 'deploy_agent needs deploy_api, which was blocked by migrate; agent_image succeeded'); + assert.equal(site.blockedBy, null, 'only a blocked deployment is blocked by something'); +}); + +test('a blocked row whose steps lead to no failure names every step that failed, and one without a workflow names none', async () => { + const cancelled = workflowRun([wfStep('image', 'prepare_image', 'cancelled'), wfStep('migrate', 'run_job', 'failed', ['image']), wfStep('other', 'deploy', 'blocked', ['migrate'])], 'cancelled'); + const loop = workflowRun([wfStep('a', 'deploy', 'blocked', ['b'], id(102)), wfStep('b', 'deploy', 'blocked', ['a']), wfStep('c', 'run_job', 'timed_out')]); + const runs = [blocked(1, API, 'resource_release', ['unknown_step'], cancelled), blocked(2, AGENT, 'harness_agent', [], loop), run(3, SITE, 'blocked', { type: 'static_site' })]; + const [api, agent, site] = (await fixture({ runs }).run('deployment-release-history', { environmentUid: ENV })).data.results; + assert.deepEqual(api.blockedBy.steps, [{ key: 'image', state: 'cancelled' }, { key: 'migrate', state: 'failed' }], 'in plan order'); + assert.equal(api.blockedBy.workflowState, 'cancelled'); + assert.deepEqual(agent.blockedBy.steps, [{ key: 'c', state: 'timed_out' }], 'a cycle of blocked steps ends, found by its deployment run uid'); + assert.equal(site.blockedBy, null, 'no workflow run, nothing to name'); +}); + +test('a wait reads its deployment with the workflow run', async () => { + const f = fixture({ waitStates: ['succeeded'] }); + assert.equal((await f.run('deployment-wait', { runUid: id(100), timeoutSeconds: 1 })).status, 'success'); + assert.equal(historyCalls(f).at(-1).query.include, 'workflow_run'); +}); + test('a deployment that ended does not keep a running stage or a growing duration', async () => { const ended = run(1, API, 'cancelled', { steps: [step(1, 'Deploy', 'running', 0)] }); ended.finished_at = null;