{"record":{"id":"c1431bb551fcfe4e","repo":"HumanSignal/label-studio","slug":"item-contains-invalid-task-field-correspondin","errorCode":null,"errorMessage":"{item} contains invalid \"task\" field: corresponding task ID couldn't be retrieved from project {project} tasks","messagePattern":"(.+?) contains invalid \"task\" field: corresponding task ID couldn't be retrieved from project (.+?) tasks","errorType":"validation","errorClass":"ValidationError","httpStatus":400,"severity":"error","filePath":"label_studio/data_import/api.py","lineNumber":622,"sourceCode":"        should_validate_label_config = project.label_config_is_not_default\n        li = LabelInterface(project.label_config) if should_validate_label_config else None\n\n        # Validate all predictions before creating any\n        validation_errors = []\n        predictions = []\n\n        for i, item in enumerate(self.request.data):\n            item = sanitize_prediction_import_payload(item)\n            # Validate task ID\n            if item.get('task') not in tasks_ids:\n                if flag_set('fflag_feat_utc_210_prediction_validation_15082025', user='auto'):\n                    validation_errors.append(\n                        f'Prediction {i}: Invalid task ID {item.get(\"task\")} - task not found in project'\n                    )\n                    continue\n                else:\n                    # Before change we raised only here\n                    raise ValidationError(\n                        f'{item} contains invalid \"task\" field: corresponding task ID couldn\\'t be retrieved '\n                        f'from project {project} tasks'\n                    )\n\n            if should_validate_label_config:\n                try:\n                    validation_errors_list = li.validate_prediction(item, return_errors=True)\n\n                    # If prediction is invalid, add error to validation_errors list and continue to next prediction\n                    if validation_errors_list:\n                        # Format errors for better readability\n                        for error in validation_errors_list:\n                            validation_errors.append(f'Prediction {i}: {error}')\n                        continue\n\n                except Exception as e:\n                    validation_errors.append(f'Prediction {i}: Error validating prediction - {extract_message(e)}')\n                    continue","sourceCodeStart":604,"sourceCodeEnd":640,"githubUrl":"https://github.com/HumanSignal/label-studio/blob/0b49e9b53917880baf1dd85d574fe5541a9aafb2/label_studio/data_import/api.py#L604-L640","documentation":"In _create_legacy (the legacy prediction creation path), if a prediction item's task ID cannot be resolved to a real task in the project — outside the code path that appends to validation_errors — it raises this ValidationError directly. It is the legacy hard-fail for unresolvable 'task' references.","triggerScenarios":"Creating predictions with an item whose 'task' ID does not match any task in the project and hits the else branch of the task lookup (e.g. lookup returned falsy in a way not captured by the earlier validation_errors path), via the predictions/import create endpoint.","commonSituations":"Same as foreign-key mismatches: cross-project or cross-instance task IDs, deleted tasks, missing 'task' key; hitting legacy code path on older deployments where the softer validation_errors accumulation is not in effect.","solutions":["Confirm the 'task' ID exists in the project before creating the prediction (GET /api/tasks/{id}/)","Re-pair predictions with their tasks by re-exporting from the source project","Remove predictions referencing deleted/nonexistent tasks from the payload","Upgrade to a version with the batched validation path, which reports all errors instead of failing on the first"],"exampleFix":"// before\ntasks = {t['id'] for t in project_tasks}\npredictions = [p for p in exported if p['task'] not in tasks]  # includes stale IDs\n// after\npredictions = [p for p in exported if p['task'] in tasks]  # only resolvable references","handlingStrategy":"validation","validationCode":"project_tasks = {t['id'] for t in paginate(f'{LS}/api/projects/{pid}/tasks')}\nfor p in predictions:\n    if p.get('task') not in project_tasks:\n        raise ValueError(f'task {p.get(\"task\")!r} not in project {pid}')","typeGuard":"def resolvable(p: dict, task_ids: set) -> bool:\n    return isinstance(p.get('task'), int) and p['task'] in task_ids","tryCatchPattern":"try:\n    requests.post(import_url, headers=H, json=payload).raise_for_status()\nexcept requests.HTTPError as e:\n    if 'corresponding task ID' in e.response.text:\n        raise SystemExit('Payload contains task references absent from this project; re-export with tasks')","preventionTips":["Resolve every 'task' ID against the live project before posting legacy prediction payloads","Purge predictions whose tasks were deleted before re-importing exports","Prefer the newer batched validation path which reports all errors at once"],"tags":["django","rest-framework","predictions","foreign-key","legacy"],"backgroundTag":"invalid-foreign-key-reference","analyzedSha":"0b49e9b53917880baf1dd85d574fe5541a9aafb2","analyzedAt":"2026-08-29T00:39:52.578Z","schemaVersion":2},"datasetVersion":"2026-08-29T02:17:18.158Z"}