Sub topic 16
Troubleshooting common import failures
This chapter assumes you can run sf data import tree and sf data upsert bulk, you know how plan files and reference IDs work, and you can read Salesforce API error codes. It gives you a repeatable way to find out why a seed load failed and fix it.
Start with where the failure happened
A failed import can stop in one of four places. Knowing which one tells you where to look.
- The CLI, before anything is sent. It cannot read the plan, a data file is missing, or the JSON is malformed.
- Authentication or org selection. The target org is wrong, or the session has expired.
- Salesforce, during the insert. Data or org configuration rejects a record. This is the most common case.
- A Bulk API job, after the command appears to succeed. The job ran, but some rows failed.
Read the error output carefully
When a tree import fails in Salesforce, the CLI prints a table of errors. Each row gives the reference ID of the record, the sObject type, and the Salesforce message. The reference ID is the most useful column. It matches the referenceId in your data file, so you can find the exact record that failed.
Run with --json when you want to script the diagnosis:
sf data import tree \
--plan data/Account-Contact-plan.json \
--target-org my-scratch \
--json > import-result.jsonThe JSON output contains the same per-record errors. This lets a CI job print only the failing reference IDs and messages.
Common error codes and what they mean
| Error code | Typical cause | Fix |
|---|---|---|
| `REQUIRED_FIELD_MISSING` | A required field is not in the data file, or the export query did not select it. | Add the field to the query and re-export, or edit the JSON. |
| `INVALID_FIELD` or `No such column` | The field does not exist in the target org yet. | Deploy project metadata before importing. |
| `INVALID_OR_NULL_FOR_RESTRICTED_PICKLIST` | The value is not in a restricted picklist in the target org. | Deploy the picklist values, or change the data. |
| `FIELD_CUSTOM_VALIDATION_EXCEPTION` | A validation rule rejected the record. | Fix the data so it passes, or bypass the rule for loads. |
| `INVALID_CROSS_REFERENCE_KEY` | A lookup points to an ID that does not exist in this org. | Replace hardcoded source-org IDs with reference IDs. |
| `MALFORMED_ID` | A field holds text where a Salesforce ID is required. | Check for a missing `@` prefix on a reference. |
| `STRING_TOO_LONG` | A value is longer than the field length in the target. | Shorten the value, or align the field definition. |
| `DUPLICATE_VALUE` | A unique field or external ID already holds the value. | Clean the org, or use upsert. |
| `DUPLICATES_DETECTED` | An active duplicate rule blocked the insert. | Deactivate the rule in the scratch org, or make the data distinct. |
| `CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY` | A trigger, flow, or process threw an error. | Read the nested message and debug the automation. |
| `UNABLE_TO_LOCK_ROW` | Parallel Bulk batches contend for the same parent record. | Use serial processing, or sort the file by parent. |
Unresolved references
Reference problems are the most frequent tree-import failure, because they depend on three settings that must agree. Take the plan file from the earlier chapter:
[
{
"sobject": "Account",
"saveRefs": true,
"resolveRefs": false,
"files": ["Accounts.json"]
},
{
"sobject": "Contact",
"saveRefs": false,
"resolveRefs": true,
"files": ["Contacts.json"]
}
]Work through these checks in order:
- Order. Parents must come before children in the plan array. If Contacts is listed first, no Account has been saved yet and
@AccountRef1cannot resolve. saveRefson the parent. If it isfalsefor Accounts, the new Account IDs are never recorded.resolveRefson the child. If it isfalsefor Contacts, the CLI sends the literal text@AccountRef1as theAccountIdvalue. This producesMALFORMED_ID.- Matching names. The
referenceIdin the Account record must be exactlyAccountRef1. Reference IDs are case sensitive, and a typo likeAcountRef1leaves the reference unresolved. - The
@prefix. Child fields use@AccountRef1. The parent's ownattributes.referenceIddoes not use@.
A child file that mixes the two styles is a common source of confusion:
{
"records": [
{
"attributes": { "type": "Contact", "referenceId": "ContactRef1" },
"LastName": "Lovelace",
"AccountId": "@AccountRef1"
}
]
}Here referenceId names this Contact, and @AccountRef1 points at a different record.
Hardcoded IDs from the source org
Exports can include fields like OwnerId, RecordTypeId, or other lookups. Salesforce IDs differ between orgs, so these values fail with INVALID_CROSS_REFERENCE_KEY or silently point at the wrong thing. Fix them in one of three ways:
- Remove the field from the export query so the target org uses its default.
- Include the related object in the plan and use a reference.
- For record types, deploy them with metadata and set the value in a script after import, for example with Apex that looks up the record type by developer name.
Check the data file for 15- or 18-character IDs before importing. A quick search catches most of them:
grep -nE '"[A-Za-z]+Id": "[a-zA-Z0-9]{15,18}"' data/*.jsonThe 200-record limit
The tree import commands handle a limited number of records per sObject, 200 in the CLI documentation. An export query with a larger LIMIT produces a file the import will refuse. Keep LIMIT at 200 or lower for tree loads. For larger sets, switch to sf data upsert bulk with a CSV, as in the bulk loading chapter.
Problems that appear only on the second run
A load that worked in a fresh scratch org often fails when you run it again in the same org. The cause is usually data already present:
- Unique fields and external IDs produce
DUPLICATE_VALUE. - Active duplicate rules produce
DUPLICATES_DETECTED. - A partial earlier run leaves parents without children, or the reverse.
Tree import always inserts. It does not update. To make a load repeatable, use upsert with an external ID, or delete the seeded records first. For a clean slate, recreating the scratch org is usually faster than hand-cleaning.
Bulk load failures
sf data upsert bulk can finish without showing every row result. If you passed --wait, the command reports whether the job completed and how many records failed. If you ran asynchronously, or the wait time expired, the job continues in Salesforce. Retrieve it with the job ID, using the sf data bulk results command in current CLI versions (check sf data --help on older installs).
Typical bulk-only issues:
- Wrong external ID name. The
--external-idvalue must match the field API name, including the__csuffix, and the field must be marked as an external ID. - CSV header mismatch. Column headers must be field API names, such as
External_Id__candName. - Encoding and delimiters. Use UTF-8 and commas. A byte order mark or semicolons can turn the first header into an unknown field.
- Date and boolean formats. Dates must be
YYYY-MM-DD, and booleanstrueorfalse. - Lock contention. Many child rows pointing at the same parent can cause
UNABLE_TO_LOCK_ROW. Sort the CSV by parent, or reduce parallelism.
The failed-record results include the original row and an error column, so you can fix those rows and rerun only them.
Validation rules, flows, and triggers
Seed data often hits automation that was designed for real users. Fix this with a method that you can repeat:
- Read the full error message. It names the rule, trigger, or flow.
- Reproduce the failure by inserting one record with an anonymous Apex script. Apex gives a stack trace and debug logs.
- Choose between making the data valid or bypassing the automation for loads.
A common bypass is a custom permission or a custom setting that automation checks. If you add one, make it deploy with the project and keep it out of production. Do not disable validation rules in a production org to make a seed pass.
Checking the result
After a successful import, confirm counts and relationships, not only the absence of errors:
sf data query \
--query "SELECT COUNT() FROM Account WHERE Industry = 'Technology'" \
--target-org my-scratch
sf data query \
--query "SELECT Account.Name, COUNT(Id) FROM Contact GROUP BY Account.Name" \
--target-org my-scratchIf Contact counts group under a null Account, references were not resolved even though the import reported success. Check resolveRefs and the @ prefix.
Exercise
You run a tree import with a plan listing Contacts before Accounts. Contacts have "AccountId": "@AccountRef1". What failure do you expect, and what is the fix?
Show answer
The CLI cannot resolve @AccountRef1 because no Account has been inserted and saved yet, so the Contact insert fails with a reference or MALFORMED_ID style error. Reorder the plan so Accounts come first, with saveRefs true, and Contacts second, with resolveRefs true.
Exercise
A seed script works in a new scratch org but fails with DUPLICATE_VALUE when you rerun it in the same org. Name two ways to make the load repeatable.
Show answer
Use sf data upsert bulk with an external ID field so existing rows are updated instead of inserted, or delete the seeded records (or recreate the scratch org) before each run.
Exercise
An import reports INVALID_CROSS_REFERENCE_KEY on OwnerId for every record. What is the probable cause, and how do you fix it?
Show answer
The export copied OwnerId values from the source org, and those user IDs do not exist in the target org. Remove OwnerId from the export query, or replace the values, so records default to the importing user.