{"record":{"id":"0fc731560758c948","repo":"HumanSignal/label-studio","slug":"failed-to-transition-state-e","errorCode":null,"errorMessage":"Failed to transition state: {e}","messagePattern":"Failed to transition state: (.+?)","errorType":"exception","errorClass":"StateManagerError","httpStatus":null,"severity":"error","filePath":"label_studio/fsm/state_manager.py","lineNumber":427,"sourceCode":"            organization_id = CurrentContext.get_organization_id()\n\n            logger.error(\n                'FSM: State transition failed',\n                extra={\n                    'event': 'fsm.transition_state_failed',\n                    'entity_type': entity._meta.label_lower,\n                    'entity_id': entity.pk,\n                    'from_state': current_state,\n                    'to_state': new_state,\n                    'error': str(e),\n                    **{\n                        'user_id': user.id if user else None,\n                        'organization_id': organization_id if organization_id else None,\n                    },\n                },\n                exc_info=True,\n            )\n            raise StateManagerError(f'Failed to transition state: {e}') from e\n\n    @classmethod\n    def get_state_history(cls, entity: Model) -> QuerySet[BaseState]:\n        \"\"\"\n        Get complete state history for an entity.\n\n        Args:\n            entity: Entity to get history for\n\n        Returns:\n            QuerySet of state records ordered by most recent first\n        \"\"\"\n        state_model = get_state_model_for_entity(entity)\n        if not state_model:\n            raise StateManagerError(\n                f'No state model registered for {entity._meta.model_name} when getting state history'\n            )\n","sourceCodeStart":409,"sourceCodeEnd":445,"githubUrl":"https://github.com/HumanSignal/label-studio/blob/0b49e9b53917880baf1dd85d574fe5541a9aafb2/label_studio/fsm/state_manager.py#L409-L445","documentation":"This is the catch-all wrap in transition_state: after validation passes, the actual state-record creation (state model save, cache update, transaction.on_commit work) raised an exception, which is re-raised as StateManagerError('Failed to transition state: ...') with full context logged (entity, transition, user, organization). The original exception is chained so the root cause is available.","triggerScenarios":"Calling transition_state where the DB insert of the new state record fails (constraint violation, deadlocked/serialized transaction, connection drop), the cache update raises, or code inside the state model's record-creation path throws. Often seen under concurrent transitions on the same entity.","commonSituations":"Two workers transitioning the same task concurrently causing deadlocks or unique-constraint conflicts; Redis outage during the immediate cache update; long transactions holding locks during bulk operations; migration drift leaving required columns missing.","solutions":["Inspect server logs — the wrapped exception is logged with exc_info plus entity/transition/user context; fix the named root cause.","Retry the transition after transient DB/Redis failures, ideally with idempotency: re-read current state and skip if the target state already applied.","Reduce contention: avoid many concurrent transitions on the same entity; queue bulk state changes.","Run pending migrations and verify the state table schema matches the installed code version."],"exampleFix":"// before\nStateManager.transition_state(task, 'completed', user=request.user)  # deadlocks under load\n\n// after\nfrom fsm.state_manager import StateManagerError\nfor attempt in range(3):\n    try:\n        StateManager.transition_state(task, 'completed', user=request.user)\n        break\n    except StateManagerError:\n        if attempt == 2:\n            logger.exception('transition failed for task %s', task.pk)\n            raise\n        time.sleep(0.5 * (attempt + 1))","handlingStrategy":"retry","validationCode":"from fsm.registry import get_state_model_for_entity\nfrom django.db import connection\n\nassert get_state_model_for_entity(entity) is not None\nconnection.ensure_connection()  # surface DB problems before attempting the transition","typeGuard":"def safe_to_transition(entity) -> bool:\n    from fsm.registry import get_state_model_for_entity\n    from django.db import connection\n    return get_state_model_for_entity(entity) is not None and connection.is_usable()","tryCatchPattern":"from fsm.state_manager import StateManagerError\nimport time\nfor attempt in range(3):\n    try:\n        StateManager.transition_state(entity, new_state, user=user)\n        break\n    except StateManagerError as e:\n        if attempt == 2:\n            logger.exception('transition failed for %s', entity.pk)\n            raise\n        time.sleep(0.5 * (2 ** attempt))","preventionTips":["Retry with exponential backoff for transient DB/cache failures; check current state first for idempotency","Avoid many simultaneous transitions on the same entity to reduce lock contention","Keep DB and Redis healthy and migrations applied; read the wrapped root cause in logs"],"tags":["database","state-manager","fsm","concurrency","wrapped-error"],"backgroundTag":"database-query-failed","analyzedSha":"0b49e9b53917880baf1dd85d574fe5541a9aafb2","analyzedAt":"2026-08-29T00:39:52.578Z","schemaVersion":2},"datasetVersion":"2026-08-29T02:17:18.158Z"}