mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-01 01:31:32 +09:00
## Summary
Fixes the race condition behind job `8a9c74ff` where a single user Retry
click caused the `audio-download-job` Cloud Run Job to run 3 times,
producing a visible "Audio download failed: Invalid state transition for
job ...: downloading -> JobStatus.DOWNLOADING" error AND
double-triggering downstream L4 GPU separation + lyrics transcription
jobs.
Root cause: the user clicked Retry inside the ~75s window between Cloud
Run's failed task and its automatic task-attempt retry. Two parallel
executions raced on job state.
## Changes
**Backend**
- `audio_download_worker.py`:
- `DOWNLOAD_ALREADY_DONE_STATUSES` idempotency guard — return success
early when status is already past `DOWNLOADING_AUDIO`, instead of
re-downloading and crashing on a redundant state transition.
- `_mark_retry_pending_if_attempts_remain` writes
`state_data.cloud_run_retry_pending = { expires_at }` when
`CLOUD_RUN_TASK_ATTEMPT < CLOUD_RUN_MAX_RETRIES` (2). Final attempt
explicitly clears any stale marker.
- `_clear_retry_pending_and_error` clears the marker and `error_message`
on successful download so the dashboard stops showing a resolved
transient failure.
- `jobs.py` `/retry` endpoint returns **409** when
`cloud_run_retry_pending` is active, preventing duplicate parallel
executions.
- `job_manager.py` error-message rendering fix: f-strings now use
`.value` consistently so we don't get the misleading `downloading ->
JobStatus.DOWNLOADING` artifact.
- `cloud_run_retry_pending` added to `SUMMARY_FIELD_PATHS` and the
dashboard prune allowlist.
**Frontend**
- `isAutoRetryPending(job)` helper in `lib/job-status.ts`.
- `JobActions`: when auto-retry is pending, hide the manual Retry button
and show "Retrying automatically…" with a spinner. Falls back to Retry
once the window expires.
- `JobCard`: don't render the `error_message` banner on completed jobs
(covers legacy data where a transient failure left a stale error
string).
- New i18n keys auto-translated to all 33 locales.
**Docs**
- `LESSONS-LEARNED.md`: Cloud Run Job retry race pattern + idempotency
defenses.
## Testing
- [x] Backend unit tests pass: 3183 passed, 36 skipped (10 new tests for
this work)
- [x] Frontend Jest tests pass: 110 passed in affected suites (8 new
tests)
- [x] TDD throughout — failing test before each implementation change
Tests added cover:
- Worker idempotency across 8 post-download statuses (`DOWNLOADING`,
`AWAITING_AUDIO_EDIT`, `TRANSCRIBING`, ... `COMPLETE`)
- Retry-pending marker: written on non-final attempt, cleared on final
attempt, cleared on success
- `_is_auto_retry_pending` helper edge cases (missing / past / future /
malformed)
- Frontend: indicator shows during window, falls back to Retry after
expiry, JobCard hides stale error on complete
## Review
- [x] Local code review completed (CodeRabbit CLI auth issue →
`feature-dev:code-reviewer` agent fallback)
- [x] Should-fix finding addressed: stale marker after final attempt
blocked manual retry for ~3 min (commit `d87cd86`)
- [ ] Optional finding deferred: frontend doesn't auto-re-render at
exact expiry time (dashboard polls, self-heals)
## Infrastructure
No Pulumi changes. `audio-download-job` `max_retries=2` retained —
automatic recovery from transient Spotify timeouts still works, and the
new idempotency guard makes retries safe.
@coderabbitai ignore
---
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
190 lines
5.2 KiB
TypeScript
190 lines
5.2 KiB
TypeScript
/**
|
|
* Tests for JobActions component
|
|
*/
|
|
|
|
import { render, screen } from '@testing-library/react'
|
|
import { JobActions } from '../job/JobActions'
|
|
import { Job } from '@/lib/api'
|
|
|
|
// Mock the API module
|
|
jest.mock('@/lib/api', () => ({
|
|
api: {
|
|
retryJob: jest.fn(),
|
|
deleteJob: jest.fn(),
|
|
},
|
|
getAccessToken: jest.fn(),
|
|
}))
|
|
|
|
// Mock the auth module
|
|
jest.mock('@/lib/auth', () => ({
|
|
useAuth: Object.assign(jest.fn(() => ({
|
|
fetchUser: jest.fn(),
|
|
})), {
|
|
getState: jest.fn(() => ({ user: { credits: 5 } })),
|
|
}),
|
|
}))
|
|
|
|
describe('JobActions', () => {
|
|
const mockOnRefresh = jest.fn()
|
|
|
|
const baseJob: Partial<Job> = {
|
|
job_id: '123',
|
|
created_at: '2025-01-01T00:00:00Z',
|
|
updated_at: '2025-01-01T00:00:00Z',
|
|
artist: 'Test Artist',
|
|
title: 'Test Song',
|
|
}
|
|
|
|
beforeEach(() => {
|
|
jest.clearAllMocks()
|
|
})
|
|
|
|
describe('Retry button visibility', () => {
|
|
it('shows retry button for failed jobs', () => {
|
|
const failedJob = { ...baseJob, status: 'failed' } as Job
|
|
render(
|
|
<JobActions
|
|
job={failedJob}
|
|
onRefresh={mockOnRefresh}
|
|
/>
|
|
)
|
|
|
|
expect(screen.getByText('Retry')).toBeInTheDocument()
|
|
})
|
|
|
|
it('does not show retry button for cancelled jobs (legacy status)', () => {
|
|
const cancelledJob = { ...baseJob, status: 'cancelled' } as Job
|
|
render(
|
|
<JobActions
|
|
job={cancelledJob}
|
|
onRefresh={mockOnRefresh}
|
|
/>
|
|
)
|
|
|
|
// Cancelled is no longer retryable - cancel now deletes the job
|
|
expect(screen.queryByText('Retry')).not.toBeInTheDocument()
|
|
})
|
|
|
|
it('does not show retry button for pending jobs', () => {
|
|
const pendingJob = { ...baseJob, status: 'pending' } as Job
|
|
render(
|
|
<JobActions
|
|
job={pendingJob}
|
|
onRefresh={mockOnRefresh}
|
|
/>
|
|
)
|
|
|
|
expect(screen.queryByText('Retry')).not.toBeInTheDocument()
|
|
})
|
|
|
|
it('does not show retry button for processing jobs', () => {
|
|
const processingJob = { ...baseJob, status: 'processing' } as Job
|
|
render(
|
|
<JobActions
|
|
job={processingJob}
|
|
onRefresh={mockOnRefresh}
|
|
/>
|
|
)
|
|
|
|
expect(screen.queryByText('Retry')).not.toBeInTheDocument()
|
|
})
|
|
|
|
it('does not show retry button for complete jobs', () => {
|
|
const completeJob = { ...baseJob, status: 'complete' } as Job
|
|
render(
|
|
<JobActions
|
|
job={completeJob}
|
|
onRefresh={mockOnRefresh}
|
|
/>
|
|
)
|
|
|
|
expect(screen.queryByText('Retry')).not.toBeInTheDocument()
|
|
})
|
|
|
|
it('shows "Retrying automatically..." instead of retry button when auto-retry is pending', () => {
|
|
const futureExpiry = new Date(Date.now() + 60 * 1000).toISOString()
|
|
const failedAutoRetryJob = {
|
|
...baseJob,
|
|
status: 'failed',
|
|
state_data: {
|
|
cloud_run_retry_pending: { expires_at: futureExpiry, expected_attempt: 1 },
|
|
},
|
|
} as Job
|
|
|
|
render(<JobActions job={failedAutoRetryJob} onRefresh={mockOnRefresh} />)
|
|
|
|
expect(screen.queryByText('Retry')).not.toBeInTheDocument()
|
|
expect(screen.getByText(/Retrying automatically/)).toBeInTheDocument()
|
|
})
|
|
|
|
it('shows retry button once auto-retry window has expired', () => {
|
|
const pastExpiry = new Date(Date.now() - 60 * 1000).toISOString()
|
|
const failedExpiredRetryJob = {
|
|
...baseJob,
|
|
status: 'failed',
|
|
state_data: {
|
|
cloud_run_retry_pending: { expires_at: pastExpiry, expected_attempt: 1 },
|
|
},
|
|
} as Job
|
|
|
|
render(<JobActions job={failedExpiredRetryJob} onRefresh={mockOnRefresh} />)
|
|
|
|
expect(screen.getByText('Retry')).toBeInTheDocument()
|
|
expect(screen.queryByText(/Retrying automatically/)).not.toBeInTheDocument()
|
|
})
|
|
})
|
|
|
|
describe('Delete button visibility', () => {
|
|
it('shows delete button for pending jobs', () => {
|
|
const pendingJob = { ...baseJob, status: 'pending' } as Job
|
|
render(
|
|
<JobActions
|
|
job={pendingJob}
|
|
onRefresh={mockOnRefresh}
|
|
/>
|
|
)
|
|
|
|
expect(screen.getByText('Delete')).toBeInTheDocument()
|
|
})
|
|
|
|
it('does not show delete button for failed jobs', () => {
|
|
const failedJob = { ...baseJob, status: 'failed' } as Job
|
|
render(
|
|
<JobActions
|
|
job={failedJob}
|
|
onRefresh={mockOnRefresh}
|
|
/>
|
|
)
|
|
|
|
expect(screen.queryByText('Delete')).not.toBeInTheDocument()
|
|
})
|
|
|
|
it('does not show delete button for complete jobs', () => {
|
|
const completeJob = { ...baseJob, status: 'complete' } as Job
|
|
render(
|
|
<JobActions
|
|
job={completeJob}
|
|
onRefresh={mockOnRefresh}
|
|
/>
|
|
)
|
|
|
|
expect(screen.queryByText('Delete')).not.toBeInTheDocument()
|
|
})
|
|
})
|
|
|
|
describe('Renders nothing when no actions available', () => {
|
|
it('returns null for complete jobs (no delete, no retry)', () => {
|
|
const completeJob = { ...baseJob, status: 'complete' } as Job
|
|
const { container } = render(
|
|
<JobActions
|
|
job={completeJob}
|
|
onRefresh={mockOnRefresh}
|
|
/>
|
|
)
|
|
|
|
// Component should render nothing when no actions are available
|
|
expect(container.firstChild).toBeNull()
|
|
})
|
|
})
|
|
})
|