Skip to content
Merged
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
48 changes: 48 additions & 0 deletions worker/src/routes/__tests__/livy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1055,6 +1055,54 @@ describe('Livy batch termination', () => {
})
})

it('keeps the killed state sticky when the list re-polls after termination (Livy 404)', async () => {
const { env, sparkDbId } = await createTestEnv()
await env.DB.prepare(`
INSERT INTO livy_batches (id, database_id, batch_id, user_id, file, class_name, created_at, status)
VALUES ('b42', ?1, 42, 'u1', 'hdfs:///app.jar', NULL, 100, 'running')
`)
.bind(sparkDbId)
.run()

// Terminate the job: Livy confirms the DELETE, the registry settles to the terminal `killed`.
mockFetchHandler = (url, init) => {
if (url === `${LIVY_URL}/batches/42` && init?.method === 'DELETE') {
return new Response(JSON.stringify({ msg: 'deleted' }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
}
return new Response('{}', { status: 404, headers: { 'Content-Type': 'application/json' } })
}

const killRes = await callWorker(env, `/api/databases/${sparkDbId}/livy/batches/42`, {
method: 'DELETE',
headers: await bearer(env, 'u1', 'member'),
})
expect(killRes.status).toBe(200)
expect(
await env.DB.prepare('SELECT status FROM livy_batches WHERE id = ?1').bind('b42').first<{ status: string }>()
).toEqual({ status: 'killed' })

// The batch is now gone from Livy, so the next list poll gets a 404. The terminal `killed`
// state must stick rather than being overwritten with `unknown`.
mockFetchHandler = () =>
new Response('Batch 42 not found', { status: 404, headers: { 'Content-Type': 'text/plain' } })

const listRes = await callWorker(env, `/api/databases/${sparkDbId}/livy/batches`, {
headers: await bearer(env, 'u1', 'member'),
})
expect(listRes.status).toBe(200)
const listJson = (await listRes.json()) as { results: Array<Record<string, unknown>> }
expect(listJson.results[0]).toMatchObject({ batch_id: 42, state: 'killed' })

expect(
await env.DB.prepare('SELECT status FROM livy_batches WHERE id = ?1').bind('b42').first<{ status: string }>()
).toEqual({
status: 'killed',
})
})

it('allows an admin to terminate another user’s job, but hides it from a non-owner with 404', async () => {
const { env, sparkDbId } = await createTestEnv()
await env.DB.prepare(`
Expand Down
38 changes: 28 additions & 10 deletions worker/src/routes/livy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,19 @@ async function activeBatchRows(c: Ctx, databaseId: string): Promise<InFlightBatc
return rows.results
}

// Writes a refreshed state back to a registry row only while that row is still in flight. A
// terminal state — most importantly the `killed` written by DELETE /batches/:batchId — must never
// be downgraded by a late or racy refresh (e.g. a list poll that read the row as in-flight just
// before the DELETE settled it). The guard keeps terminal states sticky without disturbing the
// single-flight partial unique index, which only constrains non-terminal rows.
async function writeStatusIfActive(c: Ctx, rowId: string, state: string): Promise<void> {
const T = tables(c.env)
const placeholders = TERMINAL_LIVY_STATES.map((_, i) => `?${i + 3}`).join(',')
await c.env.DB.prepare(`UPDATE ${T.livy_batches} SET status = ?1 WHERE id = ?2 AND status NOT IN (${placeholders})`)
.bind(state, rowId, ...TERMINAL_LIVY_STATES)
.run()
}

// Pulls the live state for one registered batch and writes it back to the registry when the
// answer is authoritative: a 2xx state, or a 404 (the batch is gone). A transient failure is not
// written back, so a flaky Livy read can never release the single-flight slot on its own.
Expand All @@ -315,8 +328,7 @@ async function refreshBatchStatus(c: Ctx, target: ResolvedLivyTarget, row: InFli
state = 'unknown'
}
if (state !== null) {
const T = tables(c.env)
await c.env.DB.prepare(`UPDATE ${T.livy_batches} SET status = ?1 WHERE id = ?2`).bind(state, row.id).run()
await writeStatusIfActive(c, row.id, state)
}
return state
}
Expand All @@ -328,15 +340,13 @@ async function settleBatchStatus(c: Ctx, rowId: string, res: LivyFetchResult): P
if (res.ok && res.data && typeof res.data === 'object') {
const d = res.data as Record<string, unknown>
if (typeof d.state === 'string') {
const T = tables(c.env)
await c.env.DB.prepare(`UPDATE ${T.livy_batches} SET status = ?1 WHERE id = ?2`).bind(d.state, rowId).run()
await writeStatusIfActive(c, rowId, d.state)
return d.state
}
return 'unknown'
}
if (res.status === 404) {
const T = tables(c.env)
await c.env.DB.prepare(`UPDATE ${T.livy_batches} SET status = 'unknown' WHERE id = ?1`).bind(rowId).run()
await writeStatusIfActive(c, rowId, 'unknown')
}
return 'unknown'
}
Expand Down Expand Up @@ -511,8 +521,16 @@ livy.get('/:id/livy/batches', async (c) => {

const results = await Promise.all(
rows.results.map(async (row) => {
const res = await livyFetch(target, `/batches/${encodeURIComponent(String(row.batch_id))}`)
const state = await settleBatchStatus(c, row.id, res)
// Terminal rows are settled for good: re-querying Livy for a killed batch (which Livy has
// already purged, so it answers 404) would downgrade the sticky `killed` back to `unknown`.
// Surface the stored terminal state directly and never touch the registry.
const state = isTerminalLivyState(row.status)
? row.status
: await settleBatchStatus(
c,
row.id,
await livyFetch(target, `/batches/${encodeURIComponent(String(row.batch_id))}`)
)
return {
id: row.id,
batch_id: row.batch_id,
Expand Down Expand Up @@ -549,13 +567,13 @@ livy.get('/:id/livy/batches/:batchId', async (c) => {
const batchId = encodeURIComponent(String(batchIdNum))
const res = await livyFetch(target, `/batches/${batchId}`)
if (res.status === 404) {
await c.env.DB.prepare(`UPDATE ${T.livy_batches} SET status = 'unknown' WHERE id = ?1`).bind(batchRow.id).run()
await writeStatusIfActive(c, batchRow.id, 'unknown')
return c.json({ error: 'Batch not found' }, 404)
}
if (res.ok && res.data && typeof res.data === 'object') {
const d = res.data as Record<string, unknown>
if (typeof d.state === 'string') {
await c.env.DB.prepare(`UPDATE ${T.livy_batches} SET status = ?1 WHERE id = ?2`).bind(d.state, batchRow.id).run()
await writeStatusIfActive(c, batchRow.id, d.state)
}
// The Livy batch detail's own appId is untrustworthy in client mode; surface the registry value.
return c.json({ ...d, appId: batchRow.app_id ?? null }, res.status as 200)
Expand Down