HumanSignal/label-studio · error · ValidationError

{item} contains invalid "task" field: task ID {task_id} not

Error message

{item} contains invalid "task" field: task ID {task_id} not found in project {project}

What it means

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.

Source

Thrown at label_studio/data_import/api.py:555

            # Extract task IDs for this batch
            batch_task_ids = [item.get('task') for item in batch_items]

            # Validate that all task IDs in this batch exist in the project
            # This is much more memory efficient than loading all project task IDs upfront
            existing_task_ids = set(
                Task.objects.filter(project=project, id__in=batch_task_ids).values_list('id', flat=True)
            )

            # Build predictions for this batch
            batch_predictions = []
            batch_validation_errors = []
            for batch_offset, item in enumerate(batch_items):
                item = sanitize_prediction_import_payload(item)
                task_id = item.get('task')
                prediction_index = batch_start + batch_offset

                if task_id not in existing_task_ids:
                    raise ValidationError(
                        f'{item} contains invalid "task" field: task ID {task_id} not found in project {project}'
                    )

                custom_interface_errors = self._validate_custom_interface_prediction(project, item, prediction_index)
                if custom_interface_errors:
                    batch_validation_errors.extend(custom_interface_errors)
                    continue

                batch_predictions.append(
                    Prediction(
                        task_id=task_id,
                        project_id=project.id,
                        result=Prediction.prepare_prediction_result(item.get('result'), project),
                        score=item.get('score'),
                        model_version=item.get('model_version', 'undefined'),
                    )
                )
                all_task_ids.add(task_id)

View on GitHub (pinned to 0b49e9b539)

Solutions

  1. Verify each prediction's 'task' ID exists in the target project via GET /api/tasks/{id}/
  2. Re-export data together with predictions so task IDs and predictions stay paired
  3. Import into the same project the tasks came from, or remap task IDs before import
  4. Check you are not mixing task IDs across environments (staging vs production instances)
  5. Ensure every prediction item has a non-null integer 'task' field

Example fix

// before: prediction without valid task reference
{"result": [{"type": "choices", "value": {"choices": ["pos"]}}]}
// after: task field points to an existing task in the project
{"task": 42, "result": [{"type": "choices", "value": {"choices": ["pos"]}}]}
Defensive patterns

Strategy: validation

Validate before calling

existing_ids = {t['id'] for t in paginate(f'{LS}/api/projects/{pid}/tasks')}
for p in predictions:
    tid = p.get('task')
    if not isinstance(tid, int) or tid not in existing_ids:
        raise ValueError(f'prediction references unknown task {tid!r}')

Type guard

def has_valid_task_ref(p: dict, valid_ids: set) -> bool:
    return isinstance(p.get('task'), int) and p['task'] in valid_ids

Try / catch

try:
    requests.post(import_url, headers=H, json=payload).raise_for_status()
except requests.HTTPError as e:
    if 'invalid "task" field' in e.response.text:
        remap_or_drop_items(payload)

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of HumanSignal/label-studio@0b49e9b539 (2026-08-29). Data as JSON: /api/errors/c5462a7919a25af6. Report an issue: GitHub.