Problem
The transcoding_jobs table in api/database.py (lines 153-202) has a 109-line comment block describing the state machine transitions. While the documentation is thorough, its length suggests the code itself doesn't make the state transitions clear.
Current State
States are implicitly derived from combinations of nullable fields:
claimed_at IS NULL AND completed_at IS NULL → unclaimed
claimed_at IS NOT NULL AND claim_expires_at > now() → actively claimed
- etc.
This requires reading extensive comments to understand the business logic.
Suggested Approach
Extract into an explicit state machine class:
class TranscodingJobStateMachine:
"""Manages state transitions for transcoding jobs."""
def is_unclaimed(self, job: JobRow) -> bool:
"""Job is available for workers to claim."""
return job.claimed_at is None and job.completed_at is None
def is_actively_claimed(self, job: JobRow) -> bool:
"""Worker has valid claim on this job."""
if job.claimed_at is None or job.completed_at is not None:
return False
return job.claim_expires_at > datetime.now(timezone.utc)
def is_claim_expired(self, job: JobRow) -> bool:
"""Worker's claim has expired, job can be reclaimed."""
if job.claimed_at is None or job.completed_at is not None:
return False
return job.claim_expires_at <= datetime.now(timezone.utc)
def can_transition_to(self, job: JobRow, target_state: str) -> bool:
"""Check if a state transition is valid."""
# Explicit transition rules
Benefits
- States are self-documenting
- Code reads like requirements
- Easier to test state transitions
- Comments become unnecessary
Files Affected
api/database.py
- Possibly extract to new
api/job_state.py
From code clarity review by Conway
Problem
The
transcoding_jobstable inapi/database.py(lines 153-202) has a 109-line comment block describing the state machine transitions. While the documentation is thorough, its length suggests the code itself doesn't make the state transitions clear.Current State
States are implicitly derived from combinations of nullable fields:
claimed_at IS NULL AND completed_at IS NULL→ unclaimedclaimed_at IS NOT NULL AND claim_expires_at > now()→ actively claimedThis requires reading extensive comments to understand the business logic.
Suggested Approach
Extract into an explicit state machine class:
Benefits
Files Affected
api/database.pyapi/job_state.pyFrom code clarity review by Conway