langgenius/dify · error · ValueError

patched environment variables require an id

Error message

patched environment variables require an id

What it means

Raised by the model_validator on SyncEnvironmentVariablePatchPayload when any upserted environment variable lacks a non-empty string 'id' (api/controllers/console/app/workflow.py:126-128). The patch-merge protocol requires every upsert to carry a stable id so the service can deterministically merge it. Missing/non-string/empty ids are rejected at validation time before the service runs.

Source

Thrown at api/controllers/console/app/workflow.py:128

class EnvironmentVariableResponseDict(TypedDict):
    value_type: str
    id: NotRequired[str]
    name: NotRequired[str]
    value: NotRequired[Any]
    description: NotRequired[str | None]


class SyncEnvironmentVariablePatchPayload(BaseModel):
    environment_variables: list[dict[str, Any]] = Field(default_factory=list)
    deleted_environment_variable_ids: list[str] = Field(default_factory=list)

    @model_validator(mode="after")
    def validate_patch(self) -> Self:
        """Require stable, disjoint IDs so the service can merge the patch deterministically."""
        upsert_ids = [variable.get("id") for variable in self.environment_variables]
        if any(not isinstance(variable_id, str) or not variable_id for variable_id in upsert_ids):
            raise ValueError("patched environment variables require an id")
        if len(set(upsert_ids)) != len(upsert_ids):
            raise ValueError("patched environment variable ids must be unique")
        if any(not variable_id for variable_id in self.deleted_environment_variable_ids):
            raise ValueError("deleted environment variable ids must not be empty")
        if len(set(self.deleted_environment_variable_ids)) != len(self.deleted_environment_variable_ids):
            raise ValueError("deleted environment variable ids must be unique")
        if set(upsert_ids).intersection(self.deleted_environment_variable_ids):
            raise ValueError("an environment variable cannot be upserted and deleted in the same patch")
        return self


class SyncDraftWorkflowPayload(BaseModel):
    model_config = ConfigDict(extra="forbid")

    graph: dict[str, Any]
    features: dict[str, Any]
    hash: str | None = None
    is_collaborative: bool = Field(default=False, alias="_is_collaborative")

View on GitHub (pinned to ef8544b173)

Solutions

  1. Generate a stable UUID (v4) client-side for every environment variable included in the patch and include it as a string 'id'.
  2. For existing variables being edited, reuse their existing id from the draft state.
  3. Run the payload through the same validation rules client-side before sending.

Example fix

// before: id missing on a new variable
{environment_variables: [{name:'KEY', value:'v', value_type:'string'}]}
// after: client-generated id
{environment_variables: [{id: crypto.randomUUID(), name:'KEY', value:'v', value_type:'string'}]}
Defensive patterns

Strategy: validation

Validate before calling

// Ensure every patched env var has a non-empty string id before submit
function ensureIds(vars) {
  return vars.map(v => ({...v, id: typeof v.id === 'string' && v.id ? v.id : crypto.randomUUID()}))
}
payload.environment_variable_patch.environment_variables = ensureIds(payload.environment_variable_patch.environment_variables)

Type guard

function isValidPatch(vars) {
  return Array.isArray(vars) && vars.every(v => typeof v?.id === 'string' && v.id.length > 0)
}

Try / catch

try { await syncDraft(appId, payload) } catch (e) {
  if (/require an id/.test(e.message)) { payload = withIds(payload); retry() }
  throw e
}

Prevention

When it happens

Trigger: POSTing/Syncing a draft workflow with environment_variable_patch.environment_variables entries that omit 'id', set it to null, or use a non-string value. Pydantic model_validate triggers the validator and re-raises as a ValidationError.

Common situations: Front-end creating a new env var in a patch without assigning a client-side UUID; migrating from the old full-replace payload that had no ids; null id sent for a 'new' variable; numeric id instead of string.

Related errors


AI-assisted analysis of langgenius/dify@ef8544b173 (2026-08-12). Data as JSON: /api/errors/a772dfad2876fa5a. Report an issue: GitHub.