{"record":{"id":"c5462a7919a25af6","repo":"HumanSignal/label-studio","slug":"item-contains-invalid-task-field-task-id-tas","errorCode":null,"errorMessage":"{item} contains invalid \"task\" field: task ID {task_id} not found in project {project}","messagePattern":"(.+?) contains invalid \"task\" field: task ID (.+?) not found in project (.+?)","errorType":"validation","errorClass":"ValidationError","httpStatus":400,"severity":"error","filePath":"label_studio/data_import/api.py","lineNumber":555,"sourceCode":"            # Extract task IDs for this batch\n            batch_task_ids = [item.get('task') for item in batch_items]\n\n            # Validate that all task IDs in this batch exist in the project\n            # This is much more memory efficient than loading all project task IDs upfront\n            existing_task_ids = set(\n                Task.objects.filter(project=project, id__in=batch_task_ids).values_list('id', flat=True)\n            )\n\n            # Build predictions for this batch\n            batch_predictions = []\n            batch_validation_errors = []\n            for batch_offset, item in enumerate(batch_items):\n                item = sanitize_prediction_import_payload(item)\n                task_id = item.get('task')\n                prediction_index = batch_start + batch_offset\n\n                if task_id not in existing_task_ids:\n                    raise ValidationError(\n                        f'{item} contains invalid \"task\" field: task ID {task_id} not found in project {project}'\n                    )\n\n                custom_interface_errors = self._validate_custom_interface_prediction(project, item, prediction_index)\n                if custom_interface_errors:\n                    batch_validation_errors.extend(custom_interface_errors)\n                    continue\n\n                batch_predictions.append(\n                    Prediction(\n                        task_id=task_id,\n                        project_id=project.id,\n                        result=Prediction.prepare_prediction_result(item.get('result'), project),\n                        score=item.get('score'),\n                        model_version=item.get('model_version', 'undefined'),\n                    )\n                )\n                all_task_ids.add(task_id)","sourceCodeStart":537,"sourceCodeEnd":573,"githubUrl":"https://github.com/HumanSignal/label-studio/blob/0b49e9b53917880baf1dd85d574fe5541a9aafb2/label_studio/data_import/api.py#L537-L573","documentation":"In _create_memory_efficient (bulk prediction import), each prediction item must carry a 'task' key whose value is the ID of a task already existing in the target project. The batch's task IDs are checked against the set of existing task IDs, and a prediction referencing a missing/unknown task ID raises this ValidationError naming the offending item.","triggerScenarios":"POST /api/projects/{id}/import (or predictions import path) with predictions whose 'task' value is not an existing task ID in the project: wrong project, ID from a different Label Studio instance, deleted task, or 'task' key absent so item.get('task') returns None.","commonSituations":"Copying predictions exported from project A into project B; re-importing an export after tasks were deleted; hardcoding task IDs from a staging server against production; export format where predictions are standalone objects without their task context.","solutions":["Verify each prediction's 'task' ID exists in the target project via GET /api/tasks/{id}/","Re-export data together with predictions so task IDs and predictions stay paired","Import into the same project the tasks came from, or remap task IDs before import","Check you are not mixing task IDs across environments (staging vs production instances)","Ensure every prediction item has a non-null integer 'task' field"],"exampleFix":"// before: prediction without valid task reference\n{\"result\": [{\"type\": \"choices\", \"value\": {\"choices\": [\"pos\"]}}]}\n// after: task field points to an existing task in the project\n{\"task\": 42, \"result\": [{\"type\": \"choices\", \"value\": {\"choices\": [\"pos\"]}}]}","handlingStrategy":"validation","validationCode":"existing_ids = {t['id'] for t in paginate(f'{LS}/api/projects/{pid}/tasks')}\nfor p in predictions:\n    tid = p.get('task')\n    if not isinstance(tid, int) or tid not in existing_ids:\n        raise ValueError(f'prediction references unknown task {tid!r}')","typeGuard":"def has_valid_task_ref(p: dict, valid_ids: set) -> bool:\n    return isinstance(p.get('task'), int) and p['task'] in valid_ids","tryCatchPattern":"try:\n    requests.post(import_url, headers=H, json=payload).raise_for_status()\nexcept requests.HTTPError as e:\n    if 'invalid \"task\" field' in e.response.text:\n        remap_or_drop_items(payload)","preventionTips":["Cache the target project's task ID set and filter predictions against it before import","Never reuse task IDs across projects or Label Studio instances","Re-export tasks and predictions together so references stay paired"],"tags":["django","rest-framework","predictions","foreign-key","validation"],"backgroundTag":"invalid-foreign-key-reference","analyzedSha":"0b49e9b53917880baf1dd85d574fe5541a9aafb2","analyzedAt":"2026-08-29T00:39:52.578Z","schemaVersion":2},"datasetVersion":"2026-08-29T02:17:18.158Z"}