Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/claim-not-kept.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@vercel/board': patch
---

`tasks claim`, `tasks run`, and `tasks create --claim` release a claim the CLI can't keep on this machine (its claims directory can't be written), and fail with `claim_not_kept`, instead of `unexpected_error` with the task left held for no one until its lease ends.
31 changes: 27 additions & 4 deletions packages/board/src/cli/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import { formatSchema, formatSchemas } from './schemas.ts'
import { parseSchemaId } from '../contract/data-schemas.ts'
import { block } from '../contract/blocks.ts'
import { actorName, claimLine, formatAccess, formatConformance, formatEvent, formatGrants, grantRow, formatSchedule, formatTasks, mentionedIn, reactionNames, formatSourceRead, formatSynced, formatThreadSummaries, formatThreads, terminalText, who } from './format.ts'
import { fileClaims, memoryClaims, tokenClaims, type Claims } from './claims.ts'
import { claimsDir, fileClaims, memoryClaims, tokenClaims, type Claims } from './claims.ts'
import { runCommand } from './run.ts'
import { AGENTS, allowRules, cliOf, disallow, installedHook, tilde, uninstallHook, type HookAgent } from './hooks.ts'
import { commands, filters as filterOptions, globalOptions, options, type CliCommand } from './commands.ts'
Expand Down Expand Up @@ -2371,13 +2371,36 @@ function readyLabels(values: string[], target: string, verb: 'claim' | 'run'): R
* keeps the claim. With nothing ready it fails: `nothing_ready`, or `timeout` once `--wait` ran
* out, as `wait` does. Stopped while it waits, it answers the exit code instead.
*/
/**
* Keeps a claim this run just took, for the commands after it. A claim it can't keep (its file
* can't be written) is one no later command could settle, and the board would hold the task
* for no one until its lease ended: it's released, and the run says why.
*/
async function keepClaim(claims: Claims, claim: ClaimedTask, done: string) {
try {
await claims.put(claim.task.id, { epoch: claim.epoch, token: claim.token, until: claim.until })
} catch (error) {
const why = error instanceof Error ? error.message : String(error)
const released = await claim.release().then(() => true, () => false)
throw new Failed({
class: 'unknown',
reason: 'claim_not_kept',
message: released
? `${done}, but couldn't keep its claim on this machine, so it was released.`
: `${done}, but couldn't keep its claim on this machine, or release it: it's held until ${claim.until}.`,
details: [why, `Claims are kept in ${claimsDir()}.`],
next: [{ instruction: `Make ${claimsDir()} writable, then claim it again`, argv: [...cli(), 'tasks', 'claim', claim.task.id, ...asTyped()] }],
})
}
}

async function claimFor(board: Board, claims: Claims, target: string | undefined, verb: 'claim' | 'run'): Promise<ClaimedTask | number> {
const lease = seconds('lease')
if (!flags.ready) {
for (const given of ['label', 'from', 'wait'] as const)
if (flags[given] !== undefined) throw usage(`--${given} goes with --ready, which claims the next ready task in a channel.`)
const claim = await board.tasks.claim(taskId(target), { ...(lease !== undefined ? { lease } : {}), ...(io.claimToken !== undefined ? { token: io.claimToken } : {}) })
await claims.put(claim.task.id, { epoch: claim.epoch, token: claim.token, until: claim.until })
await keepClaim(claims, claim, `Claimed task ${ref(claim.task.id)}`)
return claim
}
if (target === undefined) throw usage('Missing the channel to claim a task in: work, or work/ for all under it.', { reason: 'missing_arguments' })
Expand Down Expand Up @@ -2409,7 +2432,7 @@ async function claimFor(board: Board, claims: Claims, target: string | undefined
stop.release()
}
if (claim) {
await claims.put(claim.task.id, { epoch: claim.epoch, token: claim.token, until: claim.until })
await keepClaim(claims, claim, `Claimed task ${ref(claim.task.id)}`)
return claim
}
if (controller.signal.aborted) return stop.interrupted() ? 130 : 0
Expand Down Expand Up @@ -2517,7 +2540,7 @@ async function tasks(args: string[]): Promise<number> {
const mentions = made.mentions ? { mentions: made.mentions } : {}
if (flags.json) sayMentions(made.mentions)
if (made.claim) {
await claims.put(made.task.id, { epoch: made.claim.epoch, token: made.claim.token, until: made.claim.until })
await keepClaim(claims, made.claim, `Started task ${ref(made.task.id)}`)
printClaim(made.task, made.claim, { outcome: 'created', ...mentions })
} else if (flags.json) result({ task: made.task, outcome: 'created', ...mentions })
else out(messageRef(made.task.id))
Expand Down
32 changes: 31 additions & 1 deletion packages/board/test/cli-tasks-claims.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { cp, stat, writeFile } from 'node:fs/promises'
import { cp, mkdir, rm, stat, writeFile } from 'node:fs/promises'
import { dirname } from 'node:path'
import { join } from 'node:path'
import { describe, expect, it } from 'vitest'
import type { MessageView } from '../src/api/routes.ts'
Expand Down Expand Up @@ -228,6 +229,35 @@ describe("vb tasks, with the claim it keeps", () => {
expect((await task(id)).task).toMatchObject({ state: 'canceled', reason: 'superseded by the nightly job', claim: null })
expect(failure(await vb(['tasks', 'cancel', id, 'again', '--json']))).toMatchObject({ reason: 'task_finished', message: `Can't cancel task #${id}. It's finished.` })
}, 60_000)

it("releases a claim it can't keep, so the same profile can claim the task again", async () => {
const mine = asProfile('keeper')
// Where claims are kept can't be written: a sandbox that keeps the agent out of its config, say.
await rm(claimsDir(), { recursive: true, force: true })
await mkdir(dirname(claimsDir()), { recursive: true })
await writeFile(claimsDir(), 'not a directory')
try {
const id = await create('unkept', 'ship the fix')
const refused = failure(await vb(['tasks', 'claim', id, '--json'], mine))
expect(refused).toMatchObject({
reason: 'claim_not_kept',
message: `Claimed task #${id}, but couldn't keep its claim on this machine, so it was released.`,
next: [{ argv: ['vb', 'tasks', 'claim', id] }],
})
expect(await state(id)).toBe('ready')

const started = failure(await vb(['tasks', 'create', 'unkept', 'and another', '--claim', '--json'], mine))
expect(started.reason).toBe('claim_not_kept')
expect(started.message).toMatch(/^Started task #\d+, but couldn't keep its claim on this machine, so it was released\.$/)

// Once it can keep it, the same profile claims the task and settles it.
await rm(claimsDir(), { force: true })
await ok(['tasks', 'claim', id], mine)
expect(await ok(['tasks', 'complete', id, 'shipped'], mine)).toBe(`completed ${id}\n`)
} finally {
await rm(claimsDir(), { recursive: true, force: true })
}
}, 60_000)
})

describe('vb tasks run', () => {
Expand Down