Sub topic 16
Putting it together in a script
This chapter combines the earlier steps into one script. It creates a job, uploads a CSV, closes the upload, polls, reads the three result sets, and resubmits the rows that are worth retrying.
I assume you have read the earlier chapters on the job model, the result files, and failure handling. You also need an OAuth access token and instance URL in the environment variables SF_INSTANCE_URL and SF_ACCESS_TOKEN, and Python 3 with requests installed.
What the script must do
A one-shot script like the earlier curl examples works until the first real failure. A script you can leave unattended has to handle four things:
- It must treat
JobComplete,FailedandAbortedas the only terminal states, and stop polling after a deadline. - It must read all three result sets. Successful and failed rows are not enough, because rows can also be unprocessed.
- It must retry only errors that can succeed on a second try, such as
UNABLE_TO_LOCK_ROW. A validation error will fail identically every time. - It must stop after a fixed number of attempts and report what is left.
Design decisions
One job per attempt. A job cannot be reopened after it leaves Open. A retry is therefore a new job built from a new CSV.
Retry file format. The unprocessed file uses the original columns, so it can be resubmitted as it is. The failed file adds sf__Id and sf__Error in front of the original columns. Those two columns must be removed before resubmitting, or Salesforce rejects the header. The script rewrites every retry file with the original header.
Line endings. The job declares lineEnding as LF. Python's csv.writer emits \r\n by default, so the script passes lineterminator="\n". A mismatch between the declared and actual line ending is a common cause of garbled rows.
Which errors to retry. The script checks the sf__Error prefix. Lock contention is transient. Required-field and validation errors are not, so they go to the permanent failures file.
Safe to retry. A failed row was not saved, and an unprocessed row was never attempted. Resubmitting either cannot create duplicates for an insert.
Backoff. Polling starts at 5 seconds and doubles up to 60. Between attempts the script waits 30 seconds, so competing transactions can release their locks.
The script
Save this as bulk_load.py.
import csv
import io
import os
import sys
import time
import requests
API_VERSION = "v62.0"
TERMINAL_STATES = {"JobComplete", "Failed", "Aborted"}
RETRYABLE_PREFIXES = ("UNABLE_TO_LOCK_ROW",)
MAX_ATTEMPTS = 3
POLL_DEADLINE_SECONDS = 3600
instance = os.environ["SF_INSTANCE_URL"]
auth = {"Authorization": f"Bearer {os.environ['SF_ACCESS_TOKEN']}"}
base = f"{instance}/services/data/{API_VERSION}/jobs/ingest"
def create_job(sobject, operation, external_id=None):
body = {
"object": sobject,
"operation": operation,
"contentType": "CSV",
"lineEnding": "LF",
}
if external_id:
body["externalIdFieldName"] = external_id
resp = requests.post(base, headers=auth, json=body, timeout=60)
resp.raise_for_status()
return resp.json()["id"]
def upload_and_close(job_id, path):
with open(path, "rb") as f:
resp = requests.put(
f"{base}/{job_id}/batches",
headers={**auth, "Content-Type": "text/csv"},
data=f,
timeout=600,
)
resp.raise_for_status()
resp = requests.patch(
f"{base}/{job_id}",
headers=auth,
json={"state": "UploadComplete"},
timeout=60,
)
resp.raise_for_status()
def wait_for_job(job_id):
delay = 5
deadline = time.time() + POLL_DEADLINE_SECONDS
while time.time() < deadline:
resp = requests.get(f"{base}/{job_id}", headers=auth, timeout=60)
resp.raise_for_status()
info = resp.json()
if info["state"] in TERMINAL_STATES:
return info
time.sleep(delay)
delay = min(delay * 2, 60)
raise TimeoutError(f"Job {job_id} did not finish within the deadline")
def fetch_rows(job_id, kind):
resp = requests.get(f"{base}/{job_id}/{kind}/", headers=auth, timeout=300)
resp.raise_for_status()
text = resp.content.decode("utf-8")
return list(csv.DictReader(io.StringIO(text)))
def write_csv(path, fieldnames, rows):
with open(path, "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(
f, fieldnames=fieldnames, lineterminator="\n",
extrasaction="ignore", restval="",
)
writer.writeheader()
writer.writerows(rows)
def load(sobject, operation, path, external_id=None):
with open(path, newline="", encoding="utf-8") as f:
fieldnames = csv.DictReader(f).fieldnames
current = path
succeeded = 0
permanent = []
retry = []
for attempt in range(1, MAX_ATTEMPTS + 1):
job_id = create_job(sobject, operation, external_id)
upload_and_close(job_id, current)
info = wait_for_job(job_id)
print(
f"Attempt {attempt}: job {job_id} {info['state']}, "
f"processed={info.get('numberRecordsProcessed')}, "
f"failed={info.get('numberRecordsFailed')}"
)
if info.get("errorMessage"):
print(f" Job error: {info['errorMessage']}")
succeeded += len(fetch_rows(job_id, "successfulResults"))
retry = fetch_rows(job_id, "unprocessedrecords")
for row in fetch_rows(job_id, "failedResults"):
if row["sf__Error"].startswith(RETRYABLE_PREFIXES):
retry.append(row)
else:
permanent.append(row)
if not retry or attempt == MAX_ATTEMPTS:
break
current = f"retry_{attempt}.csv"
write_csv(current, fieldnames, retry)
print(f" Retrying {len(retry)} rows from {current}")
time.sleep(30)
permanent.extend(retry)
if permanent:
write_csv("failed_final.csv", ["sf__Error"] + fieldnames, permanent)
print(f"Succeeded: {succeeded}. Not loaded: {len(permanent)}.")
return len(permanent) == 0
if __name__ == "__main__":
ok = load("Contact", "insert", "contacts.csv")
sys.exit(0 if ok else 1)For an upsert, call load("Contact", "upsert", "contacts.csv", external_id="External_Id__c"). The CSV then needs that field as a column.
Running it
Place the CSV from the earlier chapters next to the script, then run it:
export SF_INSTANCE_URL="https://example.my.salesforce.com"
export SF_ACCESS_TOKEN="00D...your-token"
python bulk_load.pyA clean run prints one Attempt 1 line and a summary. If some rows hit lock errors, you also see a Retrying line and an Attempt 2 line. The exit code is 0 only when every row loaded, so a scheduler or CI job can react to partial failures.
Gotchas and limits of this version
- Memory.
fetch_rowsreads each result file fully into memory. That is fine for a few hundred thousand rows. For larger loads, stream the response to disk withstream=Trueand process it line by line. - Upload size. A job accepts a limited amount of data, documented as 150 MB per job at the time of writing. Check current limits, and split the file into several jobs before uploading if it is larger. This script does not split.
- Token expiry. A long poll can outlive the access token. If you expect multi-hour jobs, refresh the token on a 401 response.
- Failed jobs. If the state is
Failed,errorMessageoften explains it, for example a header naming a field that does not exist. The script prints it, but retrying rows will not fix a header problem. Check that message before trusting the retry loop. - Order of rows. Lock contention drops when records that share a parent are grouped together in the file. Sort the CSV by parent ID, for example
AccountId, before the first attempt.
Exercise
The script treats rows whose error starts with UNABLETOLOCKROW as retryable. A teammate wants to add "REQUIREDFIELDMISSING" to RETRYABLEPREFIXES so that nothing is lost. Explain why this is a mistake, and name two other changes you would make so that rows with that error are still handled sensibly.
Show answer
A missing required field is a data problem, so the same row fails the same way on every attempt. Retrying only wastes jobs and daily limits. Instead, leave it out of RETRYABLEPREFIXES so these rows go to failedfinal.csv. Then fix the source data, for example by validating required columns before upload, and reload failedfinal.csv (with the sf_Error column removed) as a new job after correcting it.
Exercise
The script passes lineterminator="\n" to csv.DictWriter and declares "lineEnding": "LF" when creating the job. What can go wrong if the retry file is written on Windows with the default settings?
Show answer
The default csv writer emits \r\n, which does not match the declared LF line ending. Salesforce can then read stray carriage returns as part of the last field, which can corrupt values or cause row errors. Setting lineterminator="\n" and opening the file with newline="" makes the bytes match the declared lineEnding.