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
71 changes: 71 additions & 0 deletions worker/src/routes/__tests__/livy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1436,6 +1436,77 @@ describe('Driver-log archive', () => {
expect(livyLogCalls).toBe(0)
})

it('backfills app_id from the driver log at archive time for a batch that never read its log while running', 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 ('b1', ?1, 202, 'u1', 'hdfs:///app.jar', NULL, 100, 'running')
`)
.bind(sparkDbId)
.run()

const logLines = [
'17/11/29 10:00:00 INFO Utils: Starting Spark',
'17/11/29 10:00:01 INFO StandaloneSchedulerBackend: Connected to Spark cluster with app ID app-20261129-0202',
'17/11/29 10:00:02 INFO StandaloneSchedulerBackend: Application registered',
]
mockFetchHandler = (url) => {
if (url === `${LIVY_URL}/batches/202`) {
return new Response(JSON.stringify({ id: 202, state: 'success' }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
}
if (url === `${LIVY_URL}/batches/202/log?from=0&size=${MAX_LOG_LINES}`) {
return new Response(JSON.stringify({ id: 202, from: 0, size: 3, total: 3, log: logLines }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
}
return new Response('{}', { status: 404, headers: { 'Content-Type': 'application/json' } })
}

const listRes = await callWorker(env, `/api/databases/${sparkDbId}/livy/batches`, {
headers: await bearer(env, 'u1', 'member'),
})
expect(listRes.status).toBe(200)

const row = await env.DB.prepare('SELECT status, app_id, log_body FROM livy_batches WHERE id = ?1')
.bind('b1')
.first<{ status: string; app_id: string | null; log_body: string | null }>()
expect(row?.status).toBe('success')
expect(row?.app_id).toBe('app-20261129-0202')
expect(row?.log_body).toBe(logLines.join('\n'))
})

it('backfills app_id from an already-archived body when the log is read from the archive', async () => {
const { env, sparkDbId } = await createTestEnv()
const logLines = [
'17/11/29 10:00:00 INFO Utils: Starting Spark',
'17/11/29 10:00:01 INFO StandaloneSchedulerBackend: Connected to Spark cluster with app ID app-20261129-0203',
]
await env.DB.prepare(`
INSERT INTO livy_batches (id, database_id, batch_id, user_id, file, class_name, created_at, status, log_body, log_truncated, log_archived_at)
VALUES ('b1', ?1, 203, 'u1', 'hdfs:///app.jar', NULL, 100, 'success', ?2, 0, 100)
`)
.bind(sparkDbId, logLines.join('\n'))
.run()

// The archived branch must not hit Livy: it serves from Zeta's copy and only backfills app_id.
mockFetchHandler = () => new Response('{}', { status: 404, headers: { 'Content-Type': 'application/json' } })

const logRes = await callWorker(env, `/api/databases/${sparkDbId}/livy/batches/203/log`, {
headers: await bearer(env, 'u1', 'member'),
})
expect(logRes.status).toBe(200)
expect(await logRes.json()).toMatchObject({ id: 203, archived: true })

const row = await env.DB.prepare('SELECT app_id FROM livy_batches WHERE id = ?1')
.bind('b1')
.first<{ app_id: string | null }>()
expect(row?.app_id).toBe('app-20261129-0203')
})

it('keeps reading live from Livy for a non-terminal batch', async () => {
const { env, sparkDbId } = await createTestEnv()
await env.DB.prepare(`
Expand Down
26 changes: 22 additions & 4 deletions worker/src/routes/livy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -387,6 +387,13 @@ async function archiveDriverLog(c: Ctx, target: ResolvedLivyTarget, rowId: strin
const data = first.data as { total?: number; log?: string[] } | null
if (!data || !Array.isArray(data.log)) return

// The "Connected to Spark cluster with app ID app-…" line appears near the head of the driver
// log, so the first `from=0` fetch is where it is found. Extract it before the tail refetch
// below reassigns `lines`, and backfill it in the same UPDATE that stores the body. This closes
// the archive race: a batch that reached its terminal state without any prior log read now
// gets its app_id at archive time instead of staying null forever.
const appId = extractAppIdFromDriverLog(data.log)

const total = typeof data.total === 'number' ? data.total : data.log.length
let lines = data.log
if (total > MAX_LOG_LINES) {
Expand All @@ -400,9 +407,9 @@ async function archiveDriverLog(c: Ctx, target: ResolvedLivyTarget, rowId: strin

const { lines: kept, truncated } = truncateLogTail(lines, MAX_LOG_BYTES, MAX_LOG_LINES)
await c.env.DB.prepare(
`UPDATE ${T.livy_batches} SET log_body = ?1, log_truncated = ?2, log_archived_at = ?3 WHERE id = ?4 AND log_body IS NULL`
`UPDATE ${T.livy_batches} SET log_body = ?1, log_truncated = ?2, log_archived_at = ?3, app_id = COALESCE(app_id, ?5) WHERE id = ?4 AND log_body IS NULL`
)
.bind(kept.join('\n'), truncated ? 1 : 0, now(), rowId)
.bind(kept.join('\n'), truncated ? 1 : 0, now(), rowId, appId)
.run()
} catch (err) {
console.error(
Expand Down Expand Up @@ -663,16 +670,27 @@ livy.get('/:id/livy/batches/:batchId/log', async (c) => {

const T = tables(c.env)
const batchRow = await c.env.DB.prepare(
`SELECT id, status, log_body, log_truncated FROM ${T.livy_batches} WHERE database_id = ?1 AND user_id = ?2 AND batch_id = ?3`
`SELECT id, status, app_id, log_body, log_truncated FROM ${T.livy_batches} WHERE database_id = ?1 AND user_id = ?2 AND batch_id = ?3`
)
.bind(target.databaseId, c.get('userId'), batchIdNum)
.first<{ id: string; status: string; log_body: string | null; log_truncated: number }>()
.first<{ id: string; status: string; app_id: string | null; log_body: string | null; log_truncated: number }>()
if (!batchRow) return c.json({ error: 'Batch not found' }, 404)

// Archive-first read: a terminal batch whose driver log was already archived is served from
// Zeta's own copy, so the log stays readable after Livy restarts or purges the batch.
if (isTerminalLivyState(batchRow.status) && batchRow.log_body !== null) {
const log = batchRow.log_body.split('\n')
// A row archived by an older worker may still carry a null app_id even though its stored body
// contains the app-id line. Backfill it here so the Spark UI button renders on the next list
// poll instead of staying missing forever.
if (batchRow.app_id == null) {
const appId = extractAppIdFromDriverLog(log)
if (appId) {
await c.env.DB.prepare(`UPDATE ${T.livy_batches} SET app_id = ?1 WHERE id = ?2 AND app_id IS NULL`)
.bind(appId, batchRow.id)
.run()
}
}
return c.json({
id: batchIdNum,
from: 0,
Expand Down