diff --git a/worker/src/routes/__tests__/livy.test.ts b/worker/src/routes/__tests__/livy.test.ts index f42ed1b..9327327 100644 --- a/worker/src/routes/__tests__/livy.test.ts +++ b/worker/src/routes/__tests__/livy.test.ts @@ -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> } + 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(` diff --git a/worker/src/routes/livy.ts b/worker/src/routes/livy.ts index a006cb0..f59cf48 100644 --- a/worker/src/routes/livy.ts +++ b/worker/src/routes/livy.ts @@ -302,6 +302,19 @@ async function activeBatchRows(c: Ctx, databaseId: string): Promise { + 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. @@ -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 } @@ -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 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' } @@ -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, @@ -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 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)