Sub topic 9
Reading successful, failed and unprocessed results
This chapter covers what to do after a Bulk API 2.0 ingest job reaches a terminal state. You will fetch three result sets, read their columns, and decide what to do with each. It assumes you can create, upload, close and monitor an ingest job, as covered in earlier chapters. It also assumes you are comfortable with HTTP calls and CSV files.
Why a finished job is not the end
A job in the JobComplete state means Salesforce finished processing. It does not mean every record succeeded. Bulk API 2.0 processes records individually, so one job can contain successes and failures together. The job also reports no per-record detail in its status response. It reports only counts.
To learn what happened to each row, you request result sets. A job has three:
| Result set | Endpoint suffix | Contains |
|---|---|---|
| Successful | `/successfulResults/` | Rows that were created or updated |
| Failed | `/failedResults/` | Rows that Salesforce rejected, with an error message |
| Unprocessed | `/unprocessedrecords/` | Rows that Salesforce never attempted |
Each endpoint is a GET on /services/data/v62.0/jobs/ingest/{jobId}/, followed by the suffix. Each returns CSV.
Checking the counts first
Before downloading anything, read the job status. The counts tell you which result sets are worth fetching.
curl "$INSTANCE_URL/services/data/v62.0/jobs/ingest/$JOB_ID" \
-H "Authorization: Bearer $ACCESS_TOKEN"The response includes these fields:
state: the job state, such asJobComplete,FailedorAborted.numberRecordsProcessed: rows Salesforce attempted.numberRecordsFailed: rows that were attempted and rejected.errorMessage: present when the whole job failed.
If numberRecordsFailed is 0, you can skip the failed results call. Downloading an empty file wastes a request, and a large job can make many such calls.
Successful results
Request the successful rows like this:
curl "$INSTANCE_URL/services/data/v62.0/jobs/ingest/$JOB_ID/successfulResults/" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-o successful.csvThe file starts with two columns that Salesforce adds, followed by your original columns:
| Column | Meaning |
|---|---|
| `sf__Id` | The ID of the record that was created or updated |
| `sf__Created` | `true` if the row created a new record, `false` if it updated an existing one |
| Your columns | The values you uploaded, in the order you uploaded them |
The sf__Created column matters most for upserts. It tells you how many rows were inserts and how many were updates. For a plain insert job, every value is true.
The sf__Id column is the main reason to keep this file. If other systems need the new Salesforce IDs, for example to store a mapping from your source key to the Salesforce record, this is where you get them.
Here is a successful results file for the Contact load from earlier chapters:
"sf__Id","sf__Created",FirstName,LastName,Email
"003xx000004TmiQAAS","true","Ada","Lovelace","[email protected]"
"003xx000004TmiRAAS","true","Alan","Turing","[email protected]"Failed results
Request the failed rows the same way:
curl "$INSTANCE_URL/services/data/v62.0/jobs/ingest/$JOB_ID/failedResults/" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-o failed.csvThe file again begins with two Salesforce columns:
| Column | Meaning |
|---|---|
| `sf__Id` | Usually empty for an insert. For update and delete it holds the ID you supplied |
| `sf__Error` | The error code and message, separated by a colon |
Your original columns follow. Here is an example with one bad row:
"sf__Id","sf__Error",FirstName,LastName,Email
"","REQUIRED_FIELD_MISSING:Required fields are missing: [LastName]:LastName --","Grace","","[email protected]"The error text starts with a status code, such as REQUIRED_FIELD_MISSING, DUPLICATE_VALUE or UNABLE_TO_LOCK_ROW. Use the code to classify failures in your scripts. Parse the human-readable message only for display, because its wording can change.
Because the failed file keeps your original columns, you can fix the data and submit it again. You must remove the sf__Id and sf__Error columns first. Salesforce treats unknown column headers as invalid, so a resubmitted file that still has them will fail. The next chapter covers resubmission in detail.
Unprocessed results
Request the unprocessed rows with this call. Note the lowercase path, which differs from the other two.
curl "$INSTANCE_URL/services/data/v62.0/jobs/ingest/$JOB_ID/unprocessedrecords/" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-o unprocessed.csvUnprocessed rows are rows that Salesforce received but never tried to load. They appear when a job ends early. This happens when a job is aborted, or when it reaches the Failed state before it works through all batches. The file contains only your original columns, with no sf__ columns, because nothing happened to these rows.
An unprocessed row is not an error. The data may be fine. You can resubmit the file as it is, in a new job.
How the three sets relate
For a job that reached a terminal state, every uploaded row ends up in exactly one set. The numbers should add up:
rows uploaded = successful + failed + unprocessedUse this as a sanity check in a script. If the counts do not match, something is wrong with your download, such as a truncated file or a request that returned an error page.
When the whole job fails
Sometimes the job ends in Failed rather than JobComplete. This means Salesforce could not process the job at all, often because of a problem in the job itself. Examples include a header that names a field that does not exist, or an upload that is not valid CSV.
In that case, read errorMessage in the job status first. The message names the cause. The failed and unprocessed result sets may still hold rows, so check the counts as you would for any other job.
A Failed job is a different problem from a job with failed rows. A JobComplete job with failed rows needs data fixes. A Failed job needs a fix to the job setup.
Reading results in code
Result files can be large. A job can hold millions of rows, so avoid loading a whole file into memory. Stream the response to disk, then read it row by row.
import csv
import os
import requests
instance = os.environ["SF_INSTANCE_URL"]
token = os.environ["SF_ACCESS_TOKEN"]
job_id = os.environ["SF_JOB_ID"]
base = f"{instance}/services/data/v62.0/jobs/ingest/{job_id}"
auth = {"Authorization": f"Bearer {token}"}
def download(suffix, path):
with requests.get(f"{base}/{suffix}/", headers=auth, stream=True) as resp:
resp.raise_for_status()
with open(path, "wb") as out:
for chunk in resp.iter_content(chunk_size=1024 * 1024):
out.write(chunk)
def count_rows(path):
with open(path, newline="", encoding="utf-8") as f:
return sum(1 for _ in csv.DictReader(f))
download("successfulResults", "successful.csv")
download("failedResults", "failed.csv")
download("unprocessedrecords", "unprocessed.csv")
ok = count_rows("successful.csv")
bad = count_rows("failed.csv")
skipped = count_rows("unprocessed.csv")
print(f"successful={ok} failed={bad} unprocessed={skipped}")
error_codes = {}
with open("failed.csv", newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
code = row["sf__Error"].split(":", 1)[0]
error_codes[code] = error_codes.get(code, 0) + 1
for code, n in sorted(error_codes.items(), key=lambda item: -item[1]):
print(code, n)The last block groups failures by error code. Grouping often shows that thousands of failed rows share one cause. Fixing that cause once is faster than reading rows one at a time.
Common errors
- Reading results before the job ends. Results are complete only when the state is
JobComplete,FailedorAborted. Poll the status first. - Assuming
JobCompletemeans success. Always comparenumberRecordsFailedwith zero. - Resubmitting the failed file as it is. The
sf__Idandsf__Errorcolumns must be removed first. - Using the wrong path for unprocessed rows. The segment is
unprocessedrecords, in lowercase, and it has no word "Results". - Discarding the successful file. It is the only complete record of the new
sf__Idvalues. Save it. - Parsing results as plain text. Fields can contain commas and line breaks inside quotes. Use a CSV parser, not
split(","). - Retaining results indefinitely. Salesforce does not keep job results forever. Download them soon after the job finishes.
Exercise
A job finishes in the JobComplete state. The status shows numberRecordsProcessed of 10000 and numberRecordsFailed of 120. Which result sets do you download, and what do you do with each?
Show answer
Download the successful results and keep the sf_Id values, since they are the new record IDs. Download the failed results, group the rows by the code at the start of sfError, fix the data, remove the sfId and sf_Error columns, and submit the rows in a new job. The unprocessed set is worth a quick check, but it should be empty because the job completed and every row was attempted.
Exercise
A resubmitted file of failed rows is rejected by Salesforce. The file still has sf_Id and sf_Error as its first two columns. What is the cause and the fix?
Show answer
Salesforce does not recognize sf_Id and sf_Error as fields on the object, so the header is invalid. Remove both columns, keep only the original data columns, and upload the file to a new ingest job.