Repository navigation
v0.5.0
Added
- A tutorial in the docs: build a small leads API with FastAPI in about 25 minutes, from the first call to tests with the fake. (#34)
- A new
esf.ApexActionFailederror (aRecordError) is raised forAPEX_FAILED, the code Salesforce returns when an Apex invocable action throws an uncaught exception. Its hint points to the Apex debug log. Code that catchesesf.RecordErrorkeeps working. - Add
sf.graphql(query, variables)for the Salesforce GraphQL API. It returns thedatamember and raisesesf.GraphQLError(with.datafor partial data) when the response has anerrorsarray, even with200 OK.sf.graphql_iter(query, variables, path=...)yields every node of a connection by followingpageInfo.endCursor, andFakeSalesforce.on_graphql()scripts answers in tests. - Add
sf.metadata.quick_deploy(validated_id), which deploys a succeeded validation without running its tests again (POST metadata/deployRequest/{id}withvalidatedDeployRequestId), andsf.metadata.cancel_deploy(id)(PATCHwithdeployResult.status=Canceling). Neither is resent once it may have reached Salesforce. Canceling a deployment that is already finalizing (API 65.0 and later) raises the newesf.DeployNotCancelable.FakeSalesforce.metadatasupports both. - Add
sf.metadatafor the Metadata API.deploy()takes zip bytes, a zip file or a folder (zipped on the fly, symlinks must stay inside it) and sendsmetadata/deployRequest.deploy_status(id, wait=True)polls until the deployment is done, andDeployResult.raise_for_errors()raisesesf.DeployFailed.retrieve(),list_metadata()anddescribe_metadata()use the SOAP Metadata API with the OAuth token;retrieve(extract_to=...)refuses zip entries that would escape the folder. Deploy and retrieve are never resent once they may have reached Salesforce, and waits end withesf.MetadataTimeout.FakeSalesforce.metadata,fake.on_deploy()andfake.add_metadata()support tests. - Add
sf.reports.recent(): the reports the user viewed most recently (GET analytics/reports, at most 200). To find any report, query theReportobject with SOQL.FakeSalesforcelists the scripted reports. - Add
sf.reportsfor the Reports and Dashboards REST API: run reports with or without filters, run slow reports asynchronously and wait withinstance(), and read or refresh dashboards.ReportResult.rows()andsummary_rows()turn fact maps into dicts, andFakeSalesforcescripts reports withfake.on_report()and dashboards withfake.on_dashboard(). New errors:ReportRunFailedandReportTimeout. - Added
default_namespace=toAsyncSalesforceandSalesforce. It sendsdefaultNamespace=<ns>inSforce-Call-Options(withclient=whenclient_nameis set), so code can name a managed package's fields without the prefix. Salesforce also leaves the prefix out of the field names it returns, so dict keys change. - Added
esf.SalesforceWarning. When Salesforce sends aWarningresponse header (for example for a deprecated API version), the client warns once per distinct text per client family, and thesf.requestevent has a newsf_warningfield. - Added
update_mru=toAsyncSalesforceandSalesforce.update_mru=FalsesendsSforce-Mru: updateMru=falseonsf.sobject(...)create, get, get-by-external-id, update and upsert, so an integration doesn't fill the user's Recently Viewed list. It needsapi_version60.0 or newer. - Collections
sf.requestevents carryrecords_failed, and thecapture()roll-up hassf_records_failed, so partial failures are visible in logs even whenraise_for_errors()is never called. - Core layer for 0.1: typed exception hierarchy, client configuration objects, result models, and pure (no-I/O) helpers for SOQL quoting, query cursors, limit-header parsing, error classification and retry decisions.
- Documentation for 0.1: a rewritten README and a documentation site covering getting started, Salesforce setup (External Client Apps), each login flow, token stores (with the durable-store contract and SQLite, SQLAlchemy and Redis example stores), records, query and search, Collections, raw requests, errors, usage and budgets, logging, performance, testing, the
esfCLI, migrating from simple-salesforce, an API reference and ADRs 0002–0011. Every Python example indocs/andREADME.mdruns in CI (tests/docs), and the docs build is strict about broken links. Public members that had no docstring now have one. - Every error has
docs_url, a link to its entry on the new Troubleshooting section of the Errors page, and some have ahintwith the likely fix: the closest field names for anInvalidField(from the cached describe only, never an extra API call), and hints forINVALID_SESSION_IDafter a refresh,API_DISABLED_FOR_ORG,REQUEST_LIMIT_EXCEEDEDand a query with an unescaped quote. Both are added tostr(error), survive pickling, andesfprints them on their own lines. - Login flows accept an Experience Cloud site URL with a path prefix as
domain=, such ashttps://acme.my.site.com/partners; the client calls the authorize, token, revoke and introspect endpoints under that URL, andJwtBeareruses the site URL as theaudclaim.ClientCredentialsstill needs the My Domain URL. - New Bulk API 2.0 job handles for long-running work.
sf.bulk.start_query()creates a query job and returns anesf.AsyncQueryJob(esf.QueryJob) at once, withid,info,refresh(),wait(),abort(),rows(parallel_downloads=)andpages(locator=, max_records=).pages()yields anesf.AsyncResultPage(esf.ResultPage) withlocator,next_locatorandsize, so a download can resume from a saved locator.sf.bulk.query_job(job_id)andsf.bulk.ingest_job(job_ids)open a job again by its ids, for example in a worker. Newesf.BulkJobNotCompletefor results asked for before a query job isJobComplete.FakeSalesforcesupports all of it. - New
esfcommands:esf describe <sObject>prints each field's type, length, whether it is required and its picklist values;esf request <METHOD> <path> [--json BODY] [--param KEY=VALUE]calls any REST resource throughsf.request; andesf generate models <sObject>... [--out FILE] [--pydantic]writes oneTypedDict(or pydantic model) per sObject from its describe, for use withmodel=. - New
private_key_passphrase=onesf.JwtBearerfor encrypted PEM keys. The client decrypts the key locally when you create the object and never sends, logs or shows the passphrase. - New
sf.bulkfor Bulk API 2.0.ingest()loads rows given as dicts, a CSV path or CSV bytes, streamed and split into jobs of at most 100 MB;Nonesets null and a missing key leaves a field unchanged. The returned job haswait(poll=esf.Backoff(...), timeout=...),info,abort(),successful_results(),failed_results()(withesf.ErrorDetail) andunprocessed_records().query()streams the rows of a query job, withinclude_deleted=andparallel_downloads=, andexpand_compound_fields()swaps compound fields for their components. Newesf.BulkJobState,esf.BulkJobInfo,esf.BulkFailure,esf.Backoffandesf.BulkJobTimeout;esf.BulkJobFailedis now raised.FakeSalesforceandAsyncFakeSalesforcesupportbulk. - New
sf.compositefor many REST calls in one round trip:builder()(Composite, up to 25 subrequests withref("id")references andall_or_none),graph()(Composite Graph, each graph atomic),tree()(sObject Tree) andbatch()(up to 25 independent subrequests). Every limit raisesValueErrorbefore anything is sent, and results areesf.CompositeResult,esf.SubrequestResultandesf.GraphResult, whoseraise_for_errors()raises the usual typed error of the subrequest that caused the failure.FakeSalesforceandAsyncFakeSalesforcesupportcomposite. - New
sf.filesfor Salesforce Files:upload()streams a path,bytes, a file object or an iterator as a multipart ContentVersion (up to 2 GB, never held in memory), with optionallink_to,share_typeandvisibility.download()is a streaming context manager; alsodownload_bytes(),download_attachment(),link()andlist_for()(returnsesf.FileLink).FakeSalesforceandAsyncFakeSalesforcesupportfiles, plusadd_file()andfile_content(). - New
sf.tooling.describe_global(cached=True)lists every Tooling API object (GET tooling/sobjects), cached likesf.describe_global().FakeSalesforceandAsyncFakeSalesforcesupport it. - New
sf.toolingfor the Tooling API:query(),query_iter()andsobject(name)(thesf.sobjectmethods ontooling/paths;sf.query_more()accepts Tooling cursors),run_tests_async(class_ids)andcompletions(type).execute_anonymous(code, capture_log=False)runs anonymous Apex and returnsesf.AnonymousResult; it is never resent after it may have reached Salesforce. Withcapture_log=Truethe client creates a short-livedTraceFlag, returns the run's debug log inresult.logand always deletes the flag.FakeSalesforceandAsyncFakeSalesforcesupporttooling, pluson_execute_anonymous()andset_completions(). - New
sf.uireads the Salesforce User Interface API:record(),object_info(),picklist_values(),create_defaults(),clone_defaults(),list_views()andlist_records(). Object info and picklist values are served from the describe cache, andFakeSalesforcehas a matchingfake.uiwithset_list_view(). - Org automation:
sf.actions.standard(),flow()andapex()run invocable actions with one input or a list, andlist()anddescribe()read them.sf.apex.get/post/put/patch/delete()call Apex REST classes and raiseApexErrorwith the decoded body.esf generate actionswrites typed stubs (dataclasses, or Pydantic models with--pydantic) that you run withsf.run().FakeSalesforcegainson_action(),set_action_describe()andon_apex(). - SOQL methods take values directly:
sf.query("SELECT Id FROM Lead WHERE Email = {}", email)onquery,query_iter,count,query_one,query_firstandexplain, quoted by the same code asesf.soql. Newsf.query_one()(exactly one row:NotFound/MultipleMatches),sf.query_first()(first row orNone),sf.explain()(query plans asQueryPlan, Salesforce Beta) andesf.flatten(row)(dotted lookup keys, flattened child rows) for CSV/DataFrame export; the CLI CSV output uses it. TokenStoreContractandAsyncTokenStoreContractcheck thatlock()excludes a second holder. They also check that a compare-and-swap save against a missing key conflicts.UNSUPPORTED_API_VERSIONmaps toUnsupportedApiVersion. A caller's ownSforce-Call-Optionsheader is merged withclient_nameinstead of replacing it.with_auth(..., instance_url=); the parent's override is no longer inherited.sf.auth.revoke()/introspect()takeauth=for tokens issued by another flow, and aStaticTokenrevoke really revokes.client_name=client option: sendsSforce-Call-Options: client=<name>on every API call so admins can attribute API usage to the integration.sf.request()refuses a body on GET/HEAD.esf migratecodemod ([migrate]extra, libcst): rewrites simple-salesforce code (sync andsimple_salesforce.aio) to even-simpler-salesforce, marks what it can't with# esf-migrate: TODO|REVIEW[rule]comments, writes a JSON report (--report), and has a CI mode (--check). See theesf migratedocs page.esf migratehas a newclient-methodsrule. It rewritesdescribe()todescribe_global()and puts a TODO onquick_search(),is_sandbox(),search(...)["searchRecords"]andlimits()["X"]["Remaining"].esf.DuplicateRules(allow_save=False, include_record_details=False, run_as_current_user=False)
controls the org's duplicate rules (Sforce-Duplicate-Rule-Header). Pass it as
duplicate_rules=tocreate(),update()andupsert()onsf.sobject(...)and
sf.collections, and onFakeSalesforce. Withinclude_record_details=True,
DuplicateDetected.duplicatescarries fields of the matched records on single-record writes.esf.sosl_term(value)quotes user input as a SOSLFIND {...}search term, escaping every SOSL reserved character so input can't close the braces or add wildcards.even_simpler_salesforce.contrib.fastapi.SalesforceIntegration([fastapi]extra): creates and closes oneAsyncSalesforcein the app lifespan, gives routes the app-wide client (admin) or a per-user child (user, throughauth_for=) as dependencies, reports theesf.capture()roll-up of each request toon_summary=, and witherror_handlers=Truemaps typed errors to JSON responses (401, 422, 404, 400 for an invalid cursor, 503 withRetry-After, 502).even_simpler_salesforce.contrib.flask.Salesforce([flask]extra): a Flask extension withinit_app()that keeps one syncSalesforceclient per app and process (ext.client), reports theesf.capture()roll-up of each request toon_summary=, and witherror_handlers=Truemaps typed errors to the same JSON responses as the FastAPI integration.sf.auth.refresh()refreshes the token now, even if it looks valid, and returns the new token, for tokens sent in a request body such as a SOAPSessionHeader. Concurrent calls share one refresh; aStaticTokenclient raisesSessionExpired.sf.collections.create(),update()andupsert()takeassignment_rule_id=andallow_save=
(Sforce-Auto-AssignandSforce-Duplicate-Rule-Header, sent on every chunk). A sandbox check
confirmed that Salesforce applies both headers to sObject Collections.sf.instance_url: read-only base URL of the org (theinstance_url=override, else the current token's instance;Nonebefore the first call). Replaces simple-salesforce'ssf_instance/base_urlfor building links.sf.leads.convert(),sf.leads.convert_many()andsf.merge()convert leads and merge duplicate leads, contacts or accounts. REST has no resource for these tasks, so the client uses the SOAP API with your OAuth token. SOAP faults map to the usual error classes, and unknown codes raiseSoapFault.FakeSalesforcesupports all three calls.sf.platform_events.publish()andpublish_many()publish platform events and return aPublishResultwith the event'sEventUuid. Publish failures raise the newEventPublishFailedandEventPublishUnavailableerrors, bothRecordErrorsubclasses.FakeSalesforcekeeps published events forfake.published(name).sf.pubsub.subscribe()receives platform events and Change Data Capture events over the
Pub/Sub API ([pubsub]extra). It decodes Avro payloads and theChangeEventHeader,
including changed, nulled and diff field bitmaps with compoundParent.Childnames, as
PubSubEventandChangeHeader(ChangeType,is_gap,is_overflow). Flow control
follows the consumer (batch_size, at most 100).AsyncReplayStore/ReplayStore, with
AsyncInMemoryReplayStore/InMemoryReplayStore, give at-least-once delivery across
restarts. The client reconnects from the last processed event, refreshes the token once on an
authentication error, and raises the newPubSubError,PubSubLimitExceededand
ReplayUnavailableerrors. Streams emitsf.pubsub.*events.esf.testingadds
fake.pubsub(emit,emit_change,fail_next) andReplayStoreContract. The client
takespubsub_endpoint=for the EU endpoint.
Changed
- Documentation site restyled: a shadcn-inspired theme and a landing home page with a step-by-step quickstart example. (#13)
- Docs: the sidebar is grouped into labelled sections, the planned API areas are on one Roadmap page, and every page is rewritten to a shorter, code-first style. ADRs are linked from the API reference instead of the header. (#23)
- Retry safety (breaking): only reads are resent after a request may have reached Salesforce.
update,delete, upsert (single and Collections) and code-running GETs (Apex REST,executeAnonymous) are no longer resent after a timeout, reset or 5xx, so triggers and flows never run twice and you never get a falseConflict/NotFound. Passidempotent=Truetosf.request()to opt in. Connect errors, row locks andRetry-Afterresponses are still retried. See ADR 0001. - Docs for
sf.actionsandActionResultnow state what a real org does: Salesforce runs at most 2,000 inputs per action request and fails the rest withUNKNOWN_EXCEPTION; an uncaught Apex exception fails every input of the request; a failed Flow interview still returnsFlow__InterviewGuidandFlow__InterviewStatusinoutputs. The platform events guide notes thatINVALID_FIELDandSTRING_TOO_LONGkeep their usual classes. - Docs landing page: FastAPI (async) and Flask (sync) examples side by side in an always-dark hero with readable code colours; the project status moved to Getting started. README: links to the docs, PyPI and changelog, badges, and a new tagline.
- Docs: dark mode by default with a working light-mode toggle (the landing hero now follows it), JetBrains Mono for code, the theme's own header, and more readable body text.
- Docs: the landing page shows one short Async/Sync example instead of two long framework apps, and six cards with code for what the library adds over simple-salesforce.
- Documented UI API and Reports API behaviour seen in a real org: an unknown object on
sf.ui.object_info()raisesForbidden(403), notInvalidType;sf.reports.dashboards.refresh()returns onlystatusUrland is refused withConflict(409) while a refresh runs andForbidden(403) within a minute of the last one; an unknown dashboard raisesInvalidReference; a dashboard component hasreportResult: Noneuntil the first refresh. - Lists of more than 2,000 inputs for an Apex or Flow action now raise
ValueErrorbefore anything is sent. Salesforce ran the first 2,000 and failed the rest. - Long-running jobs now all wait the same way as Bulk jobs:
sf.metadata.deploy_status(wait=True),sf.metadata.retrieve()andsf.reports.instance()takepoll=esf.Backoff(...)(default 2 s doubling up to 30 s) andtimeout=with a default of 3600 s instead of 600 s.sf.reports.instance()takespollinstead ofpoll_interval. - Replay now matches the query string by default, comparing SOQL with literals masked;
match_query=Falserestores the old behaviour. - The README and the roadmap page list every API area as available, now that Pub/Sub completes the release plan up to 0.5.
- The
[testing]extra no longer caps pytest below 9.2; it only skips 9.2.0 on Python 3.10, where that release crashes at startup. - The describe cache now revalidates with
If-None-Matchwhen Salesforce sent anETag, so stalesf.ui.object_info()andsf.ui.picklist_values()entries get a304instead of a full download. - The package is now marked
Development Status :: 4 - Beta. The project status notes in the README and docs list the orgs and login flow the test suite runs against. - The recorder now masks record ids and SOQL/SOSL literals by default, and names and postal addresses in sObject records (JSON objects with
attributes); a plain create or update body keeps its values.mask_ids=Falseandmask_personal=Falseturn this off,extra_keys=adds fields, and you should read every fixture before you share it. - The sdist now has an explicit file list: the source, the tests, the docs and docs config those tests read,
README.md,CHANGELOG.md,pyproject.tomland the licence files. Decimalvalues are encoded as exact JSON numbers instead of strings, with both JSON backends.OpenTelemetrymetrics no longer carry thecallerandsobjectlabels, which can take many distinct values; spans still carry them. Passmetric_attributes=to choose the metric labels.esf.flatten()given a list, a tuple, aQueryResultor another iterable of rows raises aTypeErrorthat says to use[esf.flatten(r) for r in page].sf.bulk.query()now raisesValueErrorbefore it creates a job if the SOQL selectsFIELDS(ALL)orFIELDS(CUSTOM), which Bulk API 2.0 query jobs don't support. Thesf.bulk.jobevent is now also emitted when await()poll seesrecords_failedchange (it already did forrecords_processed), and itsrecords_failedisNonefor query jobs instead of0.sf.pubsubnow decodes Date fields (Avrodoc…:DateOnly…) todatetime.dateinstead of leaving the epoch-millisecondint.FakeSalesforce.pubsubgives change events a randomevent_id, as Salesforce does.sf.request()returnsbytesfor binary bodies (any content type that is not text, XML, JSON or declared with acharset=), so file contents such asContentVersion/{id}/VersionDataarrive intact instead of being decoded with replacement characters. Text bodies are decoded with their declared charset.sf.tooling.sobject(...)no longer uses the.json/.xml/.htmlexternal id workaround, which is verified only for the REST API. The value is sent in the path.sf.ui.record()now raisesValueErrorwhen you pass bothfieldsandlayout_types. Salesforce refuses the combination with HTTP 400INVALID_INPUT_COMBINATION, so the call could never succeed.
Deprecated
BatchResult.okis deprecated in favour ofBatchResult.succeeded, becauseif batch.ok:reads like "all succeeded" but is true when any record succeeded..okemitsEsfDeprecationWarningand will be removed in 0.7; usenot batch.failedto check that every record succeeded.allow_save=oncreate(),update()andupsert()(sf.sobject(...),sf.collectionsand
FakeSalesforce) is deprecated in favour ofduplicate_rules=esf.DuplicateRules(allow_save=...).
It still sends the same header, but it emitsEsfDeprecationWarning, and passing both raises
TypeError. It will be removed in 0.7.
Removed
sobject.delete()no longer takesif_unmodified_since=. Salesforce doesn't support conditional headers onDELETE: it rejects such a request (500 UNKNOWN_EXCEPTION, or400 BAD_HEADERfor a future date) instead of checking the precondition.
Fixed
- A REST response (such as an Apex REST class's own
500) that carriesINVALID_SESSION_IDwithout HTTP401no longer refreshes the token and resends the request; only SOAP faults do. A class that returns its own401or429body now raisesApexErrorwith.body, and an Apex REST path with#is rejected. - A SOAP fault (always HTTP 500), such as
INVALID_TYPEfromsf.metadata.list_metadata()orINVALID_LOCATORfrom a retrieve, is no longer resent as if the server had failed.SERVER_UNAVAILABLEand 500 responses without a fault are still retried. - A
401withoutINVALID_SESSION_IDorinvalid_token, such as one an Apex REST class returns itself, no longer refreshes and resends a write. Reads still get one refresh and resend. - A call that waits before a retry no longer holds its
max_concurrencyplace, so it doesn't block other calls for the whole backoff. - A refresh failure that running calls may need to share stays in memory until they finish, so a waiter can't retry with an already-rotated refresh token. Idle per-token-key locks are dropped, so a client per user no longer keeps a lock per user forever.
- An HTML or plain-text HTTP 414 or 431 page (a URL or header block too long, for example a long
sf.tooling.execute_anonymous()body) now raisesRequestTooLargeinstead ofUnexpectedResponse. - An
{"error": ...}body outside/services/oauth2/, for example from an Apex REST class, is classified by its HTTP status instead of always asOAuthError, so a 404 raisesNotFound.ApexError.bodyholds the response body. - Bulk API 2.0:
failed_results()now splits the space-separated field list that Salesforce writes insf__Error(...:LastName Company --), andparallel_downloadsworks at API 59.0–62.0, whereresultPagesanswers withresultChunks/resultLink. A query that usesFIELDS(STANDARD)on an object with compound fields gets a hint saying so. - Collections chunks that fail with an HTML 5xx (proxy/maintenance page) are marked
outcome="unknown"(the request may have reached Salesforce).ESF_DEBUG=2attempt events log the path template instead of the URL, so external id values stay out of logs.parameterized_searchevents carrysoql_hash. - Collections: when one chunk's request fails, every other chunk still finishes and the call raises
PartialFailurewith the full orderedBatchResult(failed-chunk rows carryextended["outcome"]="unknown"or"rejected"). Previously the async client raised immediately and left the other chunks writing in the background, and the results of committed chunks were lost.all_or_none=Trueerrors now report the real HTTP method. - Concurrent callers whose requests were in flight when a token refresh failed now reliably share that failure (the refresh generation is captured before each request is sent).
- Describe results are private copies, so changing one no longer changes the cache. Concurrent cache misses make one request, and idle describe locks are dropped.
- Docs synced with the implementation: the changelog page explains how pre-releases (0.1.0rcN) are recorded, install instructions use
pip install --preuntil 0.1.0 final, themigrateandallextras are listed, and parameter names, event fields, error mapping,esf migrateoptions and exit codes and the API reference now match the code. - Docs: the performance page no longer lists the Bulk CSV benchmark, which the suite skips until Bulk ships in 0.3. It also says that the client waits for
Retry-Afteronly on429andREQUEST_LIMIT_EXCEEDED, and that 5xx retries use backoff. - Files: a
memoryviewupload of wider items now sends the rightContent-Length, a gzip download reportscontent_length=Noneinstead of the compressed size, a downloaded JSON file is no longer parsed as an API response, and a file the upload opened is closed as soon as a send fails. - If
sf.request()gets a 2xxapplication/jsonbody that is not valid JSON, thesf.requestevent now reportsoutcome="error". Previously the event saidokand the error was raised afterwards. - JSON request bodies containing NaN or ±Infinity (as
floatorDecimal, at any depth) now raiseValueErrorbefore anything is sent, with both the stdlib and orjson backends. Previously orjson turned them intonulland would have blanked the field in Salesforce. - New recipes: select all fields with SOQL
FIELDS()or a field list built fromdescribe()(query guide), and clear the describe cache after a deploy with your ownesf.MemoryCache(records guide). - Query events,
NotFoundandMultipleMatchesname the outer object for queries with subqueries. - Review fixes: cursors/ids/identifiers with a trailing newline are rejected (fullmatch); calls after close raise
TransportError;InMemoryTokenStore.lock()is a real per-key lock; the limits poller lives on the client family and stops with the root client;NOT_FOUNDon an sObject type raisesInvalidType; SOSLFIND {...}terms are redacted from logs;sf.auth.refreshedis emitted after the refresh lock is released; client-credentials/JWTinvalid_grantis anOAuthError, notReauthorizationRequired;capture()counts only real retries; SOQL floats never use exponent notation; JwtBearer checks for the[jwt]extra at construction. - The JWT bearer page now shows how to upload the certificate to the app and lists the
invalid_grantdescriptions Salesforce documents for this flow. - The
api_versionvalidation errors now quoteDEFAULT_API_VERSIONand the minimum supported version from their constants instead of hard-coded numbers that would go stale on the next version bump. - The docs for
UnsupportedApiVersionandsobject(...).delete()now match what Salesforce does: an
api_versionnewer than the org's givesNotFound(NOT_FOUND), and anIf-Unmodified-Since
header on DELETE is rejected (the record is kept), not ignored. - The in-memory token stores no longer reuse a version after
delete(), so a stale compare-and-swap can't overwrite a newer token, and they drop idle per-key locks.TokenStoreContractchecks the version rule too. - The query guide now says to send only signed cursors to a browser, and that a signed cursor is not bound to a user.
- The records guide now shows how to write a Pydantic model back with only the fields you changed, and no longer says that Pydantic
Decimalfields give exact numbers on read: the client parses JSON numbers asfloatfirst. - The sync client's docstring no longer calls it async.
- Usage values from
Sforce-Limit-Infoare kept per org. Awith_auth()child in another org no longer overwrites the parent'sapi_usedandapi_max, and the budget guard checks the org that the call goes to. - When many concurrent calls hit an expired session and the token refresh fails (for example
invalid_client,invalid_grantor a 401 from the token endpoint), the callers that were already waiting for that refresh now all get the same typed error instead of each posting to the token endpoint again. Bad credentials no longer cause a burst of token requests that can trip Salesforce login rate limits. A call made after the failure still makes a fresh attempt. - With refresh-token rotation, a call whose freshly refreshed token was revoked by another process's refresh now uses the newer stored token and resends (at most 2 times, never a second refresh request; the last resend holds the token store's lock), instead of raising
SessionExpired. If it still fails, the error says the token was superseded by another refresh rather than pointing at OAuth scopes or IP policies.retry_reasonsgains the valuetoken_superseded. ChangeType.SNAPSHOTis added, so a change event with it no longer ends a Pub/Sub subscription.DeployResult.failedandraise_for_errors()now count failed Apex tests. Salesforce reports a deployment whose tests failed asSucceededwhenrollback_on_erroris off (the default outside production).ErrorDetailandRecordResultare hashable.ErrorDetail.extendedstill counts for==but not forhash().FakeSalesforcematches the real client in more places: a subquery or string literal no longer changes the reported sObject,MultipleMatches.matchesholds record URLs, a closed fake raisesTransportError, andrequest()refuses a body on GET and HEAD.sf.requestevents carryrecords_failedfor Collections and includeerror_messageonly withESF_DEBUG.FakeSalesforcenow matches the real client: positional query values,query_one,query_first,explain,instance_url,with_auth(instance_url=)andsf.auth. A signature-parity test checks this, and the fake caps open query locators.GraphQLError.errorsnow reads the field path that Salesforce sends aspathsintoextended["path"], and HTML-unescapes the messages (Field 'Nmae'instead ofField 'Nmae').graphql_errorsstill holds the entries as sent.JwtBearer(domain="https://test.salesforce.com")now uses thehttps://test.salesforce.comaudience, likedomain="test".LeadConvertrejects text with control characters and values of the wrong type before building the SOAP envelope.sf.actionschecks the action name also for an empty batch, andFakeSalesforcerecords no call for one.RetryPolicy(respect_retry_after=False)now retries rate-limited calls with normal backoff instead of failing immediately. TheESF_DEBUGline prints whole thousands as100k.Sforce-Call-Optionsoptions are joined with;, as in the Salesforce example, and a caller's own header is split on both;and,before the client mergesclient=into it.calls_by_callercounts at most 1,000 distinct caller tags, so tags with many values can't grow memory without bound. Calls with a new tag after that count under"other".datetime.timevalues encode asisoformat()strings with both JSON backends. Previously the stdlib backend raisedTypeErrorand orjson rejected atimewith a timezone.esf generate actionswrites a module that loads when a description contains quotes or control characters, or a name matches a Python keyword or a name the module uses; an unwritable--outis a usage error (exit 2) and the file starts with the same header asesf generate models.esf migrate --excludenow matches directory names such asbuildandtests, skips those directories while it walks, and accepts relative globs when you pass an absolute path.esf migrate --rulesrunssobject-attrand its sub-rules as one group. Before,--rules sobject-attrrewroteupsert()andget_by_custom_id()calls tosobject()without fixing their arguments or marking them.esf migrate --writekeeps a UTF-8 byte order mark and reads and writes a file in the encoding of its PEP 263 coding comment, instead of dropping the BOM or reporting a read error.from simple_salesforce import *now gets a TODO.esf migrate --writekeeps each file's line endings and writes atomically through a uniquely named temporary file. A file it can't write is reported as an error in the results instead of aborting the run.esf migrateconfirms a client from a bareSalesforceorAsyncSalesforceonly when that name comes from simple-salesforce, so code that already uses this library stays unchanged.query(q, flag)now becomesinclude_deleted=flagor gets a TODO, and calls with*argsor**kwargsget a TODO instead of a wrong rewrite.esf migratemarks simple-salesforce exceptions constructed with arguments and thecontent,resource_nameandurlattributes of caught exceptions with a TODO. It now removes a rewritten exception import that is no longer used, and puts markers forexcept*handlers above the handler.esf migrateno longer rejects a file that uses syntax newer than the running Python, such asexcept*on Python 3.10. The compile check now runs only when the original file compiles.esf migrateputs a TODO on aquery()call whose result it can't follow, for example a result that is returned, passed on or assigned twice.QueryResultis not a dict, so these uses broke without a marker.esf migraterenames a storedget_by_custom_idmethod reference toget_by_external_idand markscreateandupsertreferences for review. Adescribe_layoutreference gets anunsupportedTODO.esf migratereview fixes: f-string-safe quoting (valid on Python 3.10/3.11) plus a compile() safety net; imports pruned only when unused (ignore[...]can no longer cause a NameError); markers for decorators, default args, class headers andmatch;ignore[rule]honoured for every sub-rule; write-mode report lines mapped with a line diff; leftover simple-salesforce imports marked; unconfirmed sObject-looking calls reported asnot-a-clientTODOs (upper-case fallback only in modules that use simple-salesforce);SalesforceExpiredSessionis a TODO (not 1:1);describe_layout,headers=/raw_response=and keywordupsert(record_id=)are TODOs; method references rewritten; un-awaited asyncquery_allis a TODO;esfname conflicts handled; stronger report redaction (multi-line strings, more secret names); faster file walk.esf.testing.record()now masks Salesforce ids used as JSON object keys (such as the UI APIrecordTypeInfos) the same way as ids in values, and keeps well-known all-zero ids such as the master record type012000000000000AAA.esf.testing.recordnow masks user names in JSON and XML (createdByName,userFullNameand similar), such as in Metadata API deploy and SOAP results.esf.testingfakes now answer like a real org (recorded on API 68.0):fake.ui.object_info()andfake.ui.list_views()raiseForbidden(403INSUFFICIENT_ACCESS) for an unknown object instead ofInvalidType, a field of another object infake.ui.record(fields=...)raisesRequestErrorINVALID_INPUT,list_views()lists__Recentfirst, UI API records and pages carry the same keys as real ones,fake.reports.recent()entries includefieldsUrl, andfake.reports.dashboards.refresh()returns onlystatusUrl.httpx.DecodingErrorandTooManyRedirectsraiseTransportError.request()decides between text andbytesfrom the parsed media type, not substrings.sf.authevents for anothertoken_keycarry that key's hash.sf.metadata.deploy_status()no longer fails withUnexpectedResponsewhen Salesforce reports the
statusFinalizing(seen on a REST quick deploy); it is treated as still in progress.sf.platform_events.publish_many()now raisesEventPublishFailedorEventPublishUnavailablewhen every request fails, aspublish()does, and the contrib helpers answerEventPublishUnavailablewith503instead of422. A SOAP session fault after a refresh now gives the connected-app hint.sf.requestevents reportoutcome="error"when a 2xx body that should be JSON is not; previously the event saidokand the error was raised afterwards.sobject(...).get_by_external_id()andupsert()now work for external id values that end in
.json,.xmlor.html. Salesforce reads those endings of the path as a response format and
answered404 NOT_FOUND; for such values the client now finds the record with SOQL (then reads it
by id) or upserts it through sObject Collections, with the same results and errors.sobject.get()is typed as returning... | Nonewhen you passif_modified_since=, because it returnsNoneon304 Not Modified.
Security
- JwtBearer infers the sandbox audience from the parsed hostname (
*.sandbox.my.salesforce.com), not a substring match, so a look-alike domain can't select the sandbox audience. - Salesforce error messages (which can quote record values) are no longer added to
sf.requestevents unlessESF_DEBUGis set; the raised exception keeps the full message. - The FastAPI and Flask examples and integration docs escape the request path before logging it, so a crafted path can't forge log lines.
- The client now checks the
instance_urlof every token from the token endpoint or a token store. A non-https URL raises an error before the bearer token is sent; plain http is allowed only for loopback hosts. - The client now raises the new
esf.TokenIdentityChanged(anAuthError) when a refreshed token, or a token it re-reads from the token store, belongs to another org or user than the token it replaces. Before, it used the new token and acted as the other user. - The default HTTP client connects directly to plain-
http://loopback hosts, so anHTTP_PROXYnever sees a bearer token in cleartext. - The recorder writes each fixture through a uniquely named temporary file, so a symlink planted at
<fixture>.tmpcan no longer redirect the write to another file. StaticToken(instance_url=...)and the client'sinstance_url=override requirehttps://(plainhttp://only forlocalhost,127.0.0.1and::1), so a bearer token is never sent unencrypted. In-memory tokens are capped at 10,000 per client family (least recently used dropped and reloaded from the store), andsf.auth.revoke()also drops the key's refresh state.WebServerFlownow requirestoken_key=(one key per Salesforce identity). Without it every user of a multi-user app shared one token record.esf query --csvprefixes string cells that start with=,+,-,@, a tab, a carriage return, a line feed or a full-width form of those signs, so spreadsheets read them as text. Table output escapes control characters, so record data can't drive the terminal.esf.testing.record()now redacts the text of every XMLsessionIdelement (theSessionHeaderof a SOAP call), whatever its format. Before, only values shaped like00D…!…were redacted.esferror lines andESF_DEBUGerror messages escape control characters, so a Salesforce error message can't send escape sequences to the terminal.repr()of anAuthStartno longer shows the PKCEcode_verifierorstate.
Performance
- Bulk API 2.0 uploads over 64 KiB are gzipped on the wire.
- The NaN and ±Infinity check on JSON request bodies no longer builds a path for every value. It finds the path only after it finds a bad value, so a 200-record chunk spends several times less time in the check.
- The describe cache stores the JSON text and each cache hit decodes its own copy after the cache lock is released, instead of deep-copying the cached dict inside the lock. A hit on a large describe is several times faster, and concurrent hits no longer queue behind each other.
- The recorder serialises each interaction once instead of on every write, which reduces the cost of long recordings.
esf migrateskips the full analysis of files that no rule can match. It checks the text, or the parsed module, for simple-salesforce, the client names and sObject-like attributes first.esf query --all --jsonprints rows page by page instead of after the last page, and--allkeeps one copy of each row instead of two.sf.collections.create(..., sobject=)validates the sObject name once per call instead of once per row.
Install: pip install even-simpler-salesforce==0.5.0