Commit 20a52631c5c for woocommerce

commit 20a52631c5cfd35dd2beea378c7a02a6f179b3b4
Author: Abdalsalaam Halawa <abdalsalaamnafez@gmail.com>
Date:   Thu Nov 26 13:49:39 2026 +0200

    [Order Fulfillments] Add the fulfillments import engine (#71025)

    * Record fulfillments import progress in the import session

    The import run needs to freeze its mapping and options on the first chunk
    and to store the resume position, counts and dedupe set after each chunk.
    record_chunk() only accepts a chunk that starts at the recorded progress,
    so a replayed chunk is never counted twice, and it keeps the last chunk's
    rows so a replay can still return them.

    * Add the fulfillments importer chunk size resolver

    The import run and the wizard need one place that decides how many CSV
    rows a request processes. The size is filterable, kept between 1 and
    1000, and capped at 25 while customer notifications are on because each
    notified row sends an email during the request.

    * Import fulfillments from a chunk of CSV rows

    import_chunk() reads the next rows with read_data_rows() and resumes from
    the byte offset of the previous result. Each row creates a fulfilled
    fulfillment with every order item, or updates the order's fulfillment
    with the same tracking number, or fails on its own with a code while the
    rest of the chunk imports. A repeated order and tracking number pair is
    skipped, tracking URLs must be http or https, and a locked fulfillment is
    not changed. Orders are loaded by ID in one query per chunk and a filter
    can map custom order numbers.

    * Parse the items column of the fulfillments CSV

    The items cell lets a row fulfill part of an order: entries are order
    item IDs or SKUs with a quantity, a repeated item is added up before it
    is checked against the ordered quantity, and an invalid cell fails the
    row with invalid_items. A blank cell fulfills every item on create and
    keeps the stored items on update, so a partial fulfillment is not widened.

    * Notify customers about imported fulfillments

    With notify_customer on, a row that fulfills a fulfillment fires the
    created notification and an update of a fulfilled one fires the updated
    notification, the same actions the fulfillments screen uses, so the
    existing customer emails are sent. A listener that throws is logged and
    the saved row still counts as imported.

    * Split saving an imported fulfillment out of the row import

    import_row() validated the cells and also built, saved and notified the
    fulfillment, about 110 lines in one method. The write half now lives in
    save_fulfillment(), and import_row() records the dedupe pair once the
    save did not fail.

    * Test the importer guards a mutation run left uncovered

    Breaking each guard once showed which ones no test noticed. Tests now
    cover URL sanitizing, a non-numeric chunk size, the use of primed orders
    and the checks on a filtered order query result, a fulfillments read that
    fails, a save that fails with an internal error, a row that fails to save
    before an identical row, SKUs and item IDs in other spellings, a line item
    whose product was deleted and one with no quantity. Checks that could not
    change any result inside one chunk are removed: the order cache lookup
    while priming, the shop_order type argument, the cache reset after a save,
    the dedupe mark on a skipped existing fulfillment, and the first-SKU-wins
    check.

    * Name the import row statuses and failure codes as constants

    The row statuses and failure codes were bare strings repeated in the
    engine, the session counts and the tests. They are now class constants
    on FulfillmentsCsvImporter. The pure fail() and get_field() helpers are
    static.

    * Require an http or https scheme and a host in imported tracking URLs

    esc_url_raw() prepends http:// to a value without a scheme, so a cell
    such as "N/A" was stored as http://N/A, and http:example.com passed
    without a host. The cell must now start with http:// or https:// and
    the sanitized URL must have a host.

    * Skip empty entries and check the sku prefix first in the items cell

    "12:1 | " failed with "Invalid items entry: ." and "sku:ABC" was
    reported as an unknown item ID "sku". Entries are now split on "|" and
    ";" with explode(), trimmed, and empty ones are skipped ("0" is kept).
    An entry starting with "sku" must have three parts, any other entry
    two, or the row fails with "Invalid items entry".

    * Fail an items entry whose SKU matches more than one line item

    Variations that inherit the parent SKU, or the same product added twice,
    gave two line items one SKU, and "sku:X:n" silently resolved to the last
    one. Such an entry now fails the row and asks for the item ID.

    * Limit imported items to what is left to fulfill on the order

    A blank items cell fulfilled every line item at the ordered quantity
    and an items cell was only checked against the ordered quantity, so
    refunds and the order's other fulfillments were ignored and an item
    could end up fulfilled more times than it was bought. The default and
    the ceiling now come from FulfillmentUtils::get_pending_items(), as in
    the bulk fulfill action. The fulfillment a row updates is left out of
    the already fulfilled side, so an update can keep its own items. A
    create with nothing left fails with no_items.

    * Map the imported provider to a known provider key or a custom provider

    The provider cell was stored as typed, so "UPS" did not match the known
    key "ups" and showed as unknown in the admin and in the orders list
    provider filter. The cell now maps to a known provider by key or name,
    ignoring case. Anything else is stored the way the fulfillment editor
    stores a custom provider: "other" plus the _provider_name meta.

    * Skip an imported update that changes nothing

    An update whose values matched the stored fulfillment was still saved,
    reported as updated and, with notifications on, emailed the customer
    again. Re-importing a file, or replaying a chunk that was imported but
    not recorded, emailed every customer a second time. When the values
    that would be written (after provider mapping and URL sanitizing) match
    the stored ones, the row is now skipped with "Fulfillment unchanged."
    and nothing is saved or sent.

    The status is only set to fulfilled when the fulfillment is not
    fulfilled yet, so an extension status that already counts as fulfilled
    is kept.

    * Keep a row imported when a listener throws after the fulfillment is written

    A listener on woocommerce_fulfillment_after_create or after_update that
    threw made the row failed although it was stored. The pair was not
    marked as seen and the fulfillments cache was stale, so a later row in
    the chunk created a second fulfillment. The interrupted action also
    stayed on $wp_current_filter, so the data store's doing_action() guard
    skipped order notes and status updates for every later row.

    A throw after the write (no pending changes left on the object) now
    reports the row as created or updated and logs the listener error. The
    filter stack is restored to its depth before the save. A new
    fulfillment is added to the cache after every save, and any real save
    failure drops the order from the cache, so a later row reloads the
    stored state instead of saving the failed row's unsaved values.

    * Fail a row that throws outside the save instead of the whole chunk

    An exception from a row outside the save and notification handlers,
    for example a resolve-order callback that throws for one order number,
    aborted the chunk after earlier rows were saved, and the caller got no
    result. The row loop now catches it, logs it, restores the filter
    stack, reports the row as failed with the new row_failed code and
    continues with the next row.

    * Notify only when the imported fulfillment is fulfilled after the save

    A before-save listener can leave the fulfillment not fulfilled; the
    customer was still notified. The notification now also requires
    get_is_fulfilled() after the save, as in OrderFulfillmentsRestController.
    The docblock says that notified means the action ran without an error,
    not that an email was sent, and the copied updated-notification
    docblock gets its 10.8.0 @since line.

    * Resolve numeric order numbers only from the primed order query

    A numeric order number that the chunk's order query did not return fell
    back to wc_get_order(), which let trashed and checkout-draft orders be
    fulfilled and their customers notified, and repeated a lookup the query
    had already answered. Numeric cells now resolve from the primed query
    only. The resolve-order filter still runs and can return any WC_Order.

    The tests also cover a trashed order and a cell such as "123x", which
    must not resolve to order 123.

    * Cut CSV values echoed in row results to 100 characters

    The order number and the messages that quote a cell had no length
    limit and are stored with the session; a thousand failed rows with long
    cells could exceed a 1 MB cache item and stall the run. Echoed values
    are now cut to 100 characters plus "...". The fail() docblock says the
    message is plain text with raw CSV values that must be escaped on
    output.

    * Detect a failed fulfillments read from the database error

    read_fulfillments() does not throw when its query fails: get_results()
    returns no rows, so the catch around it never ran and a failed read
    looked like an order without fulfillments, which turns an update into a
    duplicate. The importer now checks $wpdb->last_error after the read and
    fails the row with store_read_failed without caching the result. The
    catch is gone; a data store that throws is handled by the row boundary.
    The test breaks the real query instead of using a throwing double.

    * Refuse unsafe chunk records and store frozen run settings at once

    record_chunk() accepted an error result and reset byte_offset to 0. It
    compared the offset only with the copy loaded by this request, so two
    loads of one session could both record offset 0, and a recorded chunk
    could bring back a deleted session. A failed write left the session
    advanced in memory.

    It now refuses an error result, re-reads the stored payload and refuses
    when it is gone or its progress moved, and restores the in-memory
    payload when the write fails. The re-read narrows the window for two
    requests recording the same chunk; the caller's lock closes it.

    freeze_run_settings() only changed memory, so after load() the mapping
    was null until a chunk was recorded. It now stores the settings and
    returns whether that worked.

    * Test the import run through the session and assert targeted keys

    The resume test now drives import_chunk(), record_chunk() and load()
    the way the run endpoint will, at chunk sizes 1 to 6, checks that a
    replayed chunk is refused, that the rows match a single-chunk import
    and that the consumed rows add up to the prepare total. New tests cover
    a deleted fulfillment with the row's tracking number, the dedupe pair
    keyed by the resolved order ID, an update that fulfills an unfulfilled
    fulfillment, and the row keys before and after the order resolves.

    Full row and count-map equality checks are replaced by assertions on
    the keys each test is about.

    * Correct the importer docblocks and the importer hooks doc

    The docblocks now state the row keys and statuses of import_chunk(),
    what notified means, that lookups are cached for the life of the
    importer, that the resolve-order filter runs once per distinct order
    number, and where the rows of the last chunk are kept.

    The hooks doc says the chunk size filter sets a maximum, which values
    fall back to the default, that numeric cells arrive already matched by
    ID, which orders a numeric cell finds, how the provider cell is mapped,
    and that the importer fires the created and updated notification
    actions.

    * Say only trashed orders are left out by the numeric order lookup

    The default order query still returns checkout-draft orders, so the
    hooks doc no longer claims they are not found by ID.

    * Leave checkout-draft orders out of the numeric order lookup

    The default status list of wc_get_orders() is array_keys() of
    wc_get_order_statuses(), and the checkout draft service adds
    wc-checkout-draft to that list through the wc_order_statuses filter, so
    a numeric cell still found checkout-draft orders. The priming query now
    passes that list without wc-checkout-draft. Both order data stores
    treat an explicit status list the same way. Trashed orders were already
    left out; cancelled, failed and refunded orders are still found.

    * Decide whether an imported row was written from the data store action

    A listener on woocommerce_fulfillment_after_create or after_update that
    called a setter and then threw left pending changes on the object, so
    the written row was reported as save_failed and not notified. The
    importer now compares did_action() for the after-create or after-update
    action before and after save(); the data store fires it only once the
    row is written. On any throw the order is dropped from the cache, so a
    later row reads the stored state instead of the listener's unwritten
    values.

    * Restore the filter stack after a notification listener throws

    A notification listener that threw left its action on
    $wp_current_filter. The notification handler now restores the stack the
    way the save and row handlers do, and the three places share one
    restore_filter_stack() helper.

    * Freeze run settings on top of the stored session payload

    When the write failed, freeze_run_settings() kept the mapping in
    memory, so a retry on the same object returned true without storing
    anything. A copy loaded before another request froze the settings and
    recorded a chunk could also freeze different settings and write its
    whole stale payload over the stored settings, counts and resume
    position.

    It now reads the stored payload first: it returns false when the
    session is gone, takes over a stored mapping instead of writing, and
    otherwise writes the settings on top of the stored payload, rolling
    back to it when the write fails. The caller's lock closes the
    remaining window.

    * Check the tracking URL scheme with string functions

    The http:// or https:// prefix is now checked on the lowercased cell
    with str_starts_with() instead of a regular expression. The sanitizer
    and the host check are unchanged.

    * Assert the required row keys with assertArrayHasKey()

    The row tests compared the exact list of keys. They now check each
    required key with assertArrayHasKey() and keep the value assertions;
    assertArrayNotHasKey() is used only where order_id must be absent.

    * Use closures that unset the unused value in the lost-write filters

    The pre_update_option callbacks that simulate a lost transient write
    take both parameters, unset the unused new value and return the old
    one.

    * Drop cached fulfillments when a row throws before its save

    A row that changed a cached fulfillment in memory and then threw before
    the save handler, for example in a providers filter, left the changed
    items on the cached object, and a later row for the same tracking
    number with a blank items cell saved them. The row-level handler now
    clears the fulfillments cache, so later rows read the stored state.

    * Retry the provider lookup after the providers list throws

    known_provider_key() set the cached key map to an empty array before
    loading the providers, so a providers filter that threw once left it
    empty, and every later row stored a known provider such as "UPS" as a
    custom provider. The map is now assigned only once it is built.

    * Record a chunk on top of the stored session payload

    record_chunk() checked the stored progress but then wrote this copy's
    whole payload. A copy loaded before another copy froze the run settings
    passed both offset checks and its write removed the stored mapping and
    restored the old options. The chunk is now applied to the stored
    payload, and a failed write rolls back to it.

    * Assert the last chunk fields one by one

    The record_chunk() test compared the whole last_chunk() array. It now
    checks offset, rows and eof separately, as the PHP tests guide asks.

    * Tell a written row from a nested save by the fulfillment object

    did_action() counted every run of the after-create or after-update
    action in the request. A before-save callback that saved another
    fulfillment and then threw raised the count, so the row that was never
    written was reported as created or updated, its pair was marked as
    seen and a later matching row was skipped. A listener added for the
    save now records the write only when the action passes this
    fulfillment, and it is removed again in a finally block.

    * Drop cached fulfillments when a notification listener throws

    A notification listener that changed the fulfillment object, for
    example its tracking number, and then threw left that unsaved change on
    the cached object, so a later row with the new tracking number updated
    the stored fulfillment instead of creating one. The notification
    failure path now drops the order's cached fulfillments.

    * Assert fulfillment items by count, item ID and quantity

    The item tests compared whole item arrays. A small helper now checks
    the item count and then each item's item_id and qty, as the PHP tests
    guide asks.

    * Fold SKU case with wc_strtolower() in the items cell

    strtolower() only folds ASCII letters, so a SKU entry with an accented
    letter did not match the same SKU stored in another case. Both sides of
    the lookup now use wc_strtolower(), like the provider lookup.

    * Notify from the stored fulfillment after a listener throws

    A listener on the after-create or after-update action can change the
    fulfillment object and then throw. The row is already written, but the
    notification check read the unsaved status and skipped the notification.
    The fulfillment is now read from the store on that path.

diff --git a/docs/features/fulfillments/hooks.md b/docs/features/fulfillments/hooks.md
index 4f6f5e69cb1..74b56617420 100644
--- a/docs/features/fulfillments/hooks.md
+++ b/docs/features/fulfillments/hooks.md
@@ -5,7 +5,7 @@ sidebar_label: Hooks

 # Order fulfillments hooks

-WooCommerce exposes lifecycle hooks, status filters, provider filters, notification actions, email template hooks, and CSV importer hooks for order fulfillments. These hooks let extensions validate fulfillment data, synchronize external systems, customize tracking behavior, adjust merchant or customer-facing output, accept header names from warehouse exports, and react when a staged import file is cleaned up.
+WooCommerce exposes lifecycle hooks, status filters, provider filters, notification actions, email template hooks, and CSV importer hooks for order fulfillments. These hooks let extensions validate fulfillment data, synchronize external systems, customize tracking behavior, adjust merchant or customer-facing output, accept header names from warehouse exports, map custom order numbers and set the chunk size of a CSV import, and react when a staged import file is cleaned up.

 ## Data lifecycle filters

@@ -60,7 +60,7 @@ add_action( 'woocommerce_fulfillment_after_update', function( $fulfillment, $cha

 ## Notification actions

-These actions back the built-in customer fulfillment emails and any additional notification channel an extension wants to add.
+These actions back the built-in customer fulfillment emails and any additional notification channel an extension wants to add. The CSV importer fires the created and updated actions for imported rows when the merchant turns on customer notifications.

 | Hook | Parameters | Purpose |
 | --- | --- | --- |
@@ -183,7 +183,7 @@ add_filter( 'woocommerce_privacy_remove_fulfillment_personal_data_meta', functio

 ## CSV importer filters

-The fulfillments CSV importer recognizes five canonical columns. This filter lets a store accept the header names used by its warehouse or 3PL exports when the importer auto-detects the column mapping.
+The fulfillments CSV importer recognizes five canonical columns. The column aliases filter lets a store accept the header names used by its warehouse or 3PL exports when the importer auto-detects the column mapping.

 Aliases are normalized before matching (lowercase, with runs of non-alphanumeric characters replaced by `_`), so `PO Number` and `po_number` are the same alias. Keys that are not one of the five canonical columns are ignored, non-string aliases are dropped, and if nothing usable is left the default aliases are used.

@@ -191,6 +191,8 @@ Aliases are normalized before matching (lowercase, with runs of non-alphanumeric
 | --- | --- |
 | `woocommerce_fulfillments_csv_importer_column_aliases` | Change the accepted header names for `order_number`, `tracking_number`, `shipment_provider`, `tracking_url`, and `items`. Receives the alias map and returns the modified map. |

+The `shipment_provider` cell is matched to a provider from `woocommerce_fulfillment_shipping_providers` by key or name, ignoring case. Any other value is stored the way the fulfillment editor stores a custom provider: `other`, with the name in `_provider_name`.
+
 ```php
 add_filter( 'woocommerce_fulfillments_csv_importer_column_aliases', function( $aliases ) {
     $aliases['order_number'][]      = 'PO Number';
@@ -200,6 +202,36 @@ add_filter( 'woocommerce_fulfillments_csv_importer_column_aliases', function( $a
 } );
 ```

+Each data row names its order in the `order_number` column. By default a number is looked up as the ID of an order with a registered order status other than checkout-draft, so trashed and checkout-draft orders are not found; cancelled, failed and refunded orders are. Stores that show customers a different order number, such as a sequential-numbers plugin, can map that value to the order with the resolve filter. Return a `WC_Order`, or `null` when the order cannot be found; any other value fails the row with `order_not_found`. The filter runs at most once per distinct order number in each chunk. A numeric cell arrives already matched to the order with that ID when one exists, so a filter for numeric custom numbers must replace that match; the early return in the example keeps it.
+
+| Hook | Parameters | Purpose |
+| --- | --- | --- |
+| `woocommerce_fulfillments_csv_importer_resolve_order` | `WC_Order\|null $order`, `string $order_number` | Find the order for an `order_number` cell that is not an order ID. |
+
+```php
+add_filter( 'woocommerce_fulfillments_csv_importer_resolve_order', function( $order, $order_number ) {
+    if ( $order instanceof WC_Order || 0 !== strpos( $order_number, 'INV-' ) ) {
+        return $order;
+    }
+
+    $orders = wc_get_orders( array( 'meta_key' => '_invoice_number', 'meta_value' => $order_number, 'limit' => 1 ) );
+
+    return $orders ? $orders[0] : null;
+}, 10, 2 );
+```
+
+The import runs in chunks of CSV data rows, one request per chunk. The chunk size filter sets the most rows one request imports; a request can ask for fewer. It lets a store with slow order hooks use smaller chunks, or a fast store use larger ones. The result is kept between 1 and 1000, and at most 25 while customer notifications are on, because every notified row sends an email during the request. A value that is not numeric, or is below 1 after conversion to an integer, falls back to the default of 200.
+
+| Hook | Parameters | Purpose |
+| --- | --- | --- |
+| `woocommerce_fulfillments_csv_importer_chunk_size` | `int $chunk_size`, `bool $notify_customer` | Change the most data rows one import request processes. |
+
+```php
+add_filter( 'woocommerce_fulfillments_csv_importer_chunk_size', function( $chunk_size, $notify_customer ) {
+    return $notify_customer ? 10 : 100;
+}, 10, 2 );
+```
+
 ## CSV importer actions

 The import wizard stages the uploaded CSV and schedules its cleanup through Action Scheduler. The action fires after the import session's lifetime (one hour plus a five-minute grace period) so the staged file is removed when the wizard never finished. It also fires while the session is still live, because a later write to the session extends its lifetime after the action was scheduled. The default handler, `ImportSession::handle_cleanup_hook()`, then leaves the file alone and schedules the action again; once the session has expired it deletes the file and its attachment post. Listeners that treat the session as abandoned must check it first: `ImportSession::load( $user_id, $token )` returns `null` once the session is gone. The action is only scheduled while the `fulfillments` feature is enabled, but the handler is attached regardless of the flag so a pending cleanup still runs after the feature is turned off.
diff --git a/plugins/woocommerce/src/Admin/Features/Fulfillments/Importer/FulfillmentsCsvImporter.php b/plugins/woocommerce/src/Admin/Features/Fulfillments/Importer/FulfillmentsCsvImporter.php
index b7a24f572f4..98a596aff38 100644
--- a/plugins/woocommerce/src/Admin/Features/Fulfillments/Importer/FulfillmentsCsvImporter.php
+++ b/plugins/woocommerce/src/Admin/Features/Fulfillments/Importer/FulfillmentsCsvImporter.php
@@ -9,10 +9,18 @@ declare( strict_types=1 );

 namespace Automattic\WooCommerce\Admin\Features\Fulfillments\Importer;

+use Automattic\WooCommerce\Admin\Features\Fulfillments\DataStore\FulfillmentsDataStore;
+use Automattic\WooCommerce\Admin\Features\Fulfillments\Fulfillment;
+use Automattic\WooCommerce\Admin\Features\Fulfillments\FulfillmentException;
+use Automattic\WooCommerce\Admin\Features\Fulfillments\FulfillmentUtils;
+use Automattic\WooCommerce\Enums\OrderStatus;
+use WC_Data_Store;
+use WC_Order;
+
 defined( 'ABSPATH' ) || exit;

 /**
- * Reads a fulfillments CSV for the import wizard and for the chunked import run.
+ * Reads a fulfillments CSV for the import wizard and imports it in chunks.
  *
  * The first non-blank record is the header. Later reads return only real data rows.
  * Blank records still advance the file position and keep their physical record numbers
@@ -24,6 +32,9 @@ defined( 'ABSPATH' ) || exit;
  * is trimmed, and a data row shorter than the header is padded with empty strings, so a
  * consumer can index a row by header position without a guard.
  *
+ * Orders, providers and fulfillments looked up by import_chunk() are cached for the
+ * life of the importer; the import run builds a new importer for each chunk.
+ *
  * @internal
  * @since 11.4.0
  */
@@ -77,6 +88,34 @@ class FulfillmentsCsvImporter {
 	 */
 	private bool $conversion_failed = false;

+	/**
+	 * Orders resolved so far, keyed by the order number cell. Null means not found.
+	 *
+	 * @var array<int|string, WC_Order|null>
+	 */
+	private array $order_cache = array();
+
+	/**
+	 * Orders named by ID in the chunks imported so far, loaded in one query per chunk and keyed by order ID.
+	 *
+	 * @var array<int, WC_Order>
+	 */
+	private array $primed_orders = array();
+
+	/**
+	 * Fulfillments of an order that are not deleted, keyed by order ID.
+	 *
+	 * @var array<int, array<int, Fulfillment>>
+	 */
+	private array $fulfillments_cache = array();
+
+	/**
+	 * Known provider keys by lowercase key and name, built on first use.
+	 *
+	 * @var array<string, string>|null
+	 */
+	private ?array $provider_keys = null;
+
 	/**
 	 * Maximum number of data rows accepted per file.
 	 *
@@ -85,6 +124,44 @@ class FulfillmentsCsvImporter {
 	 */
 	public const MAX_IMPORT_ROWS = 5000;

+	/**
+	 * Data rows imported per chunk unless the chunk size filter changes it.
+	 */
+	public const DEFAULT_CHUNK_SIZE = 200;
+
+	/**
+	 * Largest chunk size accepted from the filter.
+	 */
+	public const MAX_CHUNK_SIZE = 1000;
+
+	/**
+	 * Largest chunk size while notifying customers, since every notified row sends an email.
+	 */
+	public const NOTIFY_CHUNK_SIZE = 25;
+
+	/**
+	 * Row statuses of import_chunk(); its counts use the same keys plus "notified".
+	 */
+	public const STATUS_CREATED = 'created';
+	public const STATUS_UPDATED = 'updated';
+	public const STATUS_SKIPPED = 'skipped';
+	public const STATUS_FAILED  = 'failed';
+
+	/**
+	 * Codes of a failed row.
+	 */
+	public const CODE_MISSING_ORDER_NUMBER    = 'missing_order_number';
+	public const CODE_MISSING_TRACKING_NUMBER = 'missing_tracking_number';
+	public const CODE_MISSING_PROVIDER        = 'missing_provider';
+	public const CODE_INVALID_TRACKING_URL    = 'invalid_tracking_url';
+	public const CODE_ORDER_NOT_FOUND         = 'order_not_found';
+	public const CODE_INVALID_ITEMS           = 'invalid_items';
+	public const CODE_STORE_READ_FAILED       = 'store_read_failed';
+	public const CODE_FULFILLMENT_LOCKED      = 'fulfillment_locked';
+	public const CODE_NO_ITEMS                = 'no_items';
+	public const CODE_SAVE_FAILED             = 'save_failed';
+	public const CODE_ROW_FAILED              = 'row_failed';
+
 	/**
 	 * Spellings accepted for a tab delimiter, since multipart and JSON clients
 	 * cannot always send a raw tab character.
@@ -103,7 +180,7 @@ class FulfillmentsCsvImporter {
 	 *
 	 * @param string               $file    Absolute path to the CSV file.
 	 * @param array<string, mixed> $options Importer options. Header parsing and row reading use delimiter and
-	 *                                      enclosure; the other two are kept for the import run.
+	 *                                      enclosure; import_chunk() also uses the other two.
 	 *                                      - notify_customer (bool): Whether to fire customer notifications. Default false.
 	 *                                      - delimiter (string): Single-character CSV delimiter. Default ','.
 	 *                                      - enclosure (string): Single-byte CSV enclosure. A line break, a non-ASCII byte,
@@ -174,6 +251,37 @@ class FulfillmentsCsvImporter {
 		return $enclosure;
 	}

+	/**
+	 * Number of data rows to import per chunk.
+	 *
+	 * The filtered value is kept between 1 and MAX_CHUNK_SIZE, and at most NOTIFY_CHUNK_SIZE
+	 * when customers are notified, so a chunk stays within typical request time limits.
+	 *
+	 * @since 11.4.0
+	 *
+	 * @param bool $notify_customer Whether the import sends customer notifications.
+	 * @return int
+	 */
+	public static function resolve_chunk_size( bool $notify_customer = false ): int {
+		/**
+		 * Filter the number of CSV data rows the fulfillments importer processes per request.
+		 *
+		 * The result is kept between 1 and 1000, and at most 25 while customer notifications
+		 * are on. A value that is not a positive number falls back to the default.
+		 *
+		 * @since 11.4.0
+		 *
+		 * @param int  $chunk_size      Default chunk size (200).
+		 * @param bool $notify_customer Whether the import sends customer notifications.
+		 */
+		$size = apply_filters( 'woocommerce_fulfillments_csv_importer_chunk_size', self::DEFAULT_CHUNK_SIZE, $notify_customer );
+		$size = is_numeric( $size ) ? (int) $size : 0;
+		if ( $size < 1 ) {
+			$size = self::DEFAULT_CHUNK_SIZE;
+		}
+		return min( $size, $notify_customer ? self::NOTIFY_CHUNK_SIZE : self::MAX_CHUNK_SIZE );
+	}
+
 	/**
 	 * Whether a delimiter input is one of the accepted spellings of a tab character.
 	 *
@@ -327,6 +435,675 @@ class FulfillmentsCsvImporter {
 		}
 	}

+	/**
+	 * Import the next chunk of data rows as fulfillments.
+	 *
+	 * A row creates a fulfilled fulfillment, updates the order's fulfillment with the same
+	 * tracking number (compared without case), or fails on its own with a code while the
+	 * rest of the chunk imports. An update that would change nothing is skipped. Pass the
+	 * previous result back as `$state` to continue; an empty state starts after the header.
+	 * A chunk-level problem returns `error` and writes nothing.
+	 *
+	 * Each row has `row`, `order_number`, `status` (created, updated, skipped or failed) and
+	 * `message`; a failed row adds `code`. `order_id` is set once the order resolves, and
+	 * `fulfillment_id` when the row matches or saves a fulfillment. A created or updated row
+	 * adds `notified`: whether the notification action ran without an error, which is not
+	 * proof that an email was sent. Messages are plain text and can quote CSV values.
+	 *
+	 * @since 11.4.0
+	 *
+	 * @param int                  $limit   Data rows to import. Capped by resolve_chunk_size(), which is also used when 0 or less.
+	 * @param array<int, string>   $mapping CSV column index => canonical column key.
+	 * @param array<string, mixed> $state {
+	 *     Resume state; a previous result can be passed as is.
+	 *
+	 *     @type int                 $byte_offset         Position to resume from. 0 starts after the header.
+	 *     @type int                 $next_record_number  Physical record number at byte_offset.
+	 *     @type array<string, true> $seen_tracking_pairs Order and tracking number pairs imported so far.
+	 * }
+	 * @return array{
+	 *     counts?: array{created:int, updated:int, skipped:int, failed:int, notified:int},
+	 *     rows?: array<int, array<string, mixed>>,
+	 *     seen_tracking_pairs?: array<string, true>,
+	 *     consumed?: int,
+	 *     byte_offset?: int,
+	 *     next_record_number?: int,
+	 *     eof?: bool,
+	 *     error?: array{code:string, message:string}
+	 * }
+	 */
+	public function import_chunk( int $limit, array $mapping, array $state = array() ): array {
+		$header_map = self::mapping_to_header_map( $mapping );
+		$missing    = self::find_missing_required_columns( $header_map );
+		if ( array() !== $missing ) {
+			return $this->error(
+				'missing_required_columns',
+				sprintf(
+					/* translators: %s: comma-separated list of missing column names. */
+					__( 'The column mapping is missing required columns: %s.', 'woocommerce' ),
+					implode( ', ', $missing )
+				)
+			);
+		}
+
+		$max  = self::resolve_chunk_size( $this->options['notify_customer'] );
+		$read = $this->read_data_rows(
+			0,
+			$limit > 0 ? min( $limit, $max ) : $max,
+			array(
+				'byte_offset'   => (int) ( $state['byte_offset'] ?? 0 ),
+				'record_number' => (int) ( $state['next_record_number'] ?? 0 ),
+			)
+		);
+		if ( isset( $read['error'] ) ) {
+			return $read;
+		}
+
+		/**
+		 * Pairs imported by earlier chunks.
+		 *
+		 * @var array<string, true> $seen
+		 */
+		$seen = is_array( $state['seen_tracking_pairs'] ?? null ) ? $state['seen_tracking_pairs'] : array();
+		$rows = array();
+		$data = $read['rows'] ?? array();
+
+		$hook_depth = count( $GLOBALS['wp_current_filter'] );
+		$this->prime_orders( $data, $header_map );
+		foreach ( $data as $row ) {
+			$order_number = self::get_field( $row['cells'], $header_map, self::COL_ORDER_NUMBER );
+			try {
+				$result = $this->import_row( $row['cells'], $header_map, $order_number, $row['row_number'], $seen );
+			} catch ( \Throwable $e ) {
+				// One row that throws, for example in a resolve-order callback, must not stop the chunk.
+				self::restore_filter_stack( $hook_depth );
+				// The row may have changed a cached fulfillment it never saved, so later rows read again.
+				$this->fulfillments_cache = array();
+				wc_get_logger()->error(
+					sprintf( 'Fulfillments import could not import row %1$d: %2$s', $row['row_number'], $e->getMessage() ),
+					array( 'source' => 'fulfillments-importer' )
+				);
+				$result = self::fail( self::CODE_ROW_FAILED, __( 'Could not import this row.', 'woocommerce' ) );
+			}
+			$rows[] = array(
+				'row'          => $row['row_number'],
+				'order_number' => self::clip( $order_number ),
+			) + $result;
+		}
+
+		$statuses = array_count_values( array_column( $rows, 'status' ) );
+		return array(
+			'counts'              => array(
+				self::STATUS_CREATED => $statuses[ self::STATUS_CREATED ] ?? 0,
+				self::STATUS_UPDATED => $statuses[ self::STATUS_UPDATED ] ?? 0,
+				self::STATUS_SKIPPED => $statuses[ self::STATUS_SKIPPED ] ?? 0,
+				self::STATUS_FAILED  => $statuses[ self::STATUS_FAILED ] ?? 0,
+				'notified'           => count( array_filter( array_column( $rows, 'notified' ) ) ),
+			),
+			'rows'                => $rows,
+			'seen_tracking_pairs' => $seen,
+			'consumed'            => (int) ( $read['consumed'] ?? 0 ),
+			'byte_offset'         => (int) ( $read['byte_offset'] ?? 0 ),
+			'next_record_number'  => (int) ( $read['next_record_number'] ?? 0 ),
+			'eof'                 => ! empty( $read['eof'] ),
+		);
+	}
+
+	/**
+	 * Validate one data row and create or update its fulfillment.
+	 *
+	 * @param array<int, string>  $cells        Trimmed cells, padded to the header width.
+	 * @param array<string, int>  $header_map   Canonical column key => CSV column index.
+	 * @param string              $order_number Order number cell.
+	 * @param int                 $row_number   Physical record number, for the log.
+	 * @param array<string, true> $seen         Pairs imported so far; a pair is added once its row lands.
+	 * @return array<string, mixed> Status and message, plus code, order_id, fulfillment_id and notified when they apply.
+	 */
+	private function import_row( array $cells, array $header_map, string $order_number, int $row_number, array &$seen ): array {
+		$tracking_number = self::get_field( $cells, $header_map, self::COL_TRACKING_NUMBER );
+		$provider        = self::get_field( $cells, $header_map, self::COL_PROVIDER );
+		$tracking_url    = self::get_field( $cells, $header_map, self::COL_TRACKING_URL );
+
+		if ( '' === $order_number ) {
+			return self::fail( self::CODE_MISSING_ORDER_NUMBER, __( 'Missing order number.', 'woocommerce' ) );
+		}
+		if ( '' === $tracking_number ) {
+			return self::fail( self::CODE_MISSING_TRACKING_NUMBER, __( 'Missing tracking number.', 'woocommerce' ) );
+		}
+		if ( '' === $provider ) {
+			return self::fail( self::CODE_MISSING_PROVIDER, __( 'Missing shipment provider.', 'woocommerce' ) );
+		}
+		if ( '' !== $tracking_url ) {
+			$tracking_url = $this->sanitize_tracking_url( $tracking_url );
+			if ( '' === $tracking_url ) {
+				return self::fail( self::CODE_INVALID_TRACKING_URL, __( 'Tracking URL must be a valid http or https URL.', 'woocommerce' ) );
+			}
+		}
+
+		$order = $this->resolve_order( $order_number );
+		if ( null === $order ) {
+			return self::fail(
+				self::CODE_ORDER_NOT_FOUND,
+				/* translators: %s: order number from the CSV. */
+				sprintf( __( 'Order not found for order number "%s".', 'woocommerce' ), self::clip( $order_number ) )
+			);
+		}
+		$order_id = $order->get_id();
+
+		// The set is stored with the session, so pairs are hashed to a fixed length.
+		$pair = substr( md5( $order_id . '|' . strtolower( $tracking_number ) ), 0, 20 );
+		if ( isset( $seen[ $pair ] ) ) {
+			return array(
+				'status'   => self::STATUS_SKIPPED,
+				'message'  => __( 'Duplicate order and tracking number in this file.', 'woocommerce' ),
+				'order_id' => $order_id,
+			);
+		}
+
+		try {
+			$existing = $this->find_existing_fulfillment( $order_id, $tracking_number );
+		} catch ( \RuntimeException $e ) {
+			return self::fail( self::CODE_STORE_READ_FAILED, __( 'Could not read the fulfillments of this order. Please try again.', 'woocommerce' ), $order_id );
+		}
+
+		$pending    = $this->pending_items( $order, $existing );
+		$items_cell = self::get_field( $cells, $header_map, self::COL_ITEMS );
+		$items      = '' === $items_cell ? null : $this->parse_items( $items_cell, $order, $pending );
+		if ( is_string( $items ) ) {
+			return self::fail( self::CODE_INVALID_ITEMS, $items, $order_id );
+		}
+		if ( null === $items && null === $existing ) {
+			// A blank items cell fulfills what is left on create, but keeps the stored items on update.
+			$items = array();
+			foreach ( $pending as $item_id => $qty ) {
+				$items[] = array(
+					'item_id' => $item_id,
+					'qty'     => $qty,
+				);
+			}
+		}
+
+		if ( null !== $existing && ! $this->options['update_existing'] ) {
+			return array(
+				'status'         => self::STATUS_SKIPPED,
+				'message'        => __( 'Fulfillment with this tracking number already exists.', 'woocommerce' ),
+				'order_id'       => $order_id,
+				'fulfillment_id' => $existing->get_id(),
+			);
+		}
+		if ( null !== $existing && $existing->is_locked() ) {
+			return self::fail( self::CODE_FULFILLMENT_LOCKED, __( 'The fulfillment with this tracking number is locked and cannot be changed.', 'woocommerce' ), $order_id );
+		}
+
+		$result = $this->save_fulfillment(
+			$order,
+			$existing,
+			$items,
+			array(
+				'tracking_number' => $tracking_number,
+				'provider'        => $provider,
+				'tracking_url'    => $tracking_url,
+			),
+			$row_number
+		);
+		if ( self::STATUS_FAILED !== $result['status'] ) {
+			$seen[ $pair ] = true;
+		}
+		return $result;
+	}
+
+	/**
+	 * Create a fulfilled fulfillment for the order, or update the matching one, and notify the customer when asked.
+	 *
+	 * @param WC_Order                                                            $order      Order of the row.
+	 * @param Fulfillment|null                                                    $existing   Fulfillment with the row's tracking number, if any.
+	 * @param array<int, array{item_id:int, qty:int}>|null                        $items      Items to store; null keeps the stored items of an update.
+	 * @param array{tracking_number:string, provider:string, tracking_url:string} $fields     Validated cells; the URL may be empty.
+	 * @param int                                                                 $row_number Physical record number, for the log.
+	 * @return array<string, mixed> Row result without the row number and order number.
+	 */
+	private function save_fulfillment( WC_Order $order, ?Fulfillment $existing, ?array $items, array $fields, int $row_number ): array {
+		$order_id      = $order->get_id();
+		$fulfillment   = $existing ?? new Fulfillment();
+		$was_fulfilled = null !== $existing && $existing->get_is_fulfilled();
+		if ( null === $existing ) {
+			if ( array() === $items ) {
+				return self::fail( self::CODE_NO_ITEMS, __( 'This order has no items left to fulfill.', 'woocommerce' ), $order_id );
+			}
+			$fulfillment->set_entity_type( WC_Order::class );
+			$fulfillment->set_entity_id( (string) $order_id );
+		}
+		if ( null !== $items ) {
+			$fulfillment->set_items( $items );
+		}
+		if ( ! $fulfillment->get_is_fulfilled() ) {
+			$fulfillment->set_status( 'fulfilled' );
+		}
+		$fulfillment->set_tracking_number( $fields['tracking_number'] );
+		$provider_key = $this->known_provider_key( $fields['provider'] );
+		// An unknown provider is stored the way the fulfillment editor stores a custom one.
+		$fulfillment->set_shipment_provider( '' !== $provider_key ? $provider_key : 'other' );
+		if ( '' === $provider_key ) {
+			$fulfillment->update_meta_data( '_provider_name', $fields['provider'] );
+		}
+		// A blank URL cell keeps the stored URL on an update.
+		if ( '' !== $fields['tracking_url'] ) {
+			$fulfillment->set_tracking_url( $fields['tracking_url'] );
+		}
+		if ( null !== $existing && array() === $fulfillment->get_changes() ) {
+			return array(
+				'status'         => self::STATUS_SKIPPED,
+				'message'        => __( 'Fulfillment unchanged.', 'woocommerce' ),
+				'order_id'       => $order_id,
+				'fulfillment_id' => $existing->get_id(),
+			);
+		}
+
+		$hook_depth = count( $GLOBALS['wp_current_filter'] );
+		// The data store fires this action with the fulfillment only once its row is written.
+		$written_hook = null === $existing ? 'woocommerce_fulfillment_after_create' : 'woocommerce_fulfillment_after_update';
+		$written      = false;
+		$mark_written = static function ( $saved ) use ( $fulfillment, &$written ) {
+			if ( $saved === $fulfillment ) {
+				$written = true;
+			}
+		};
+		add_action( $written_hook, $mark_written, PHP_INT_MIN );
+		try {
+			$fulfillment->save();
+		} catch ( \Throwable $e ) {
+			self::restore_filter_stack( $hook_depth );
+			wc_get_logger()->error(
+				sprintf( 'Fulfillments import could not save row %1$d for order %2$d: %3$s', $row_number, $order_id, $e->getMessage() ),
+				array( 'source' => 'fulfillments-importer' )
+			);
+			// The cached fulfillment may hold values that were not written, so the next row reads it again.
+			unset( $this->fulfillments_cache[ $order_id ] );
+			if ( ! $written ) {
+				return self::fail( self::CODE_SAVE_FAILED, $e instanceof FulfillmentException ? $e->getMessage() : __( 'Could not save the fulfillment.', 'woocommerce' ), $order_id );
+			}
+			// The listener may have changed the object after the write, so the notification uses the stored row.
+			$fulfillment = new Fulfillment( (string) $fulfillment->get_id() );
+		} finally {
+			remove_action( $written_hook, $mark_written, PHP_INT_MIN );
+		}
+		if ( null === $existing && isset( $this->fulfillments_cache[ $order_id ] ) ) {
+			$this->fulfillments_cache[ $order_id ][] = $fulfillment;
+		}
+
+		return array(
+			'status'         => null === $existing ? self::STATUS_CREATED : self::STATUS_UPDATED,
+			'message'        => null === $existing ? __( 'Fulfillment created.', 'woocommerce' ) : __( 'Fulfillment updated.', 'woocommerce' ),
+			'order_id'       => $order_id,
+			'fulfillment_id' => $fulfillment->get_id(),
+			'notified'       => $this->options['notify_customer'] && $fulfillment->get_is_fulfilled() && $this->notify_customer( $order, $fulfillment, $was_fulfilled, $row_number ),
+		);
+	}
+
+	/**
+	 * Fire the customer notification the fulfillments screen fires for the same change.
+	 *
+	 * The row is already saved, so a listener that throws is logged and the row still
+	 * counts as imported. True means the action ran, not that an email was sent: the
+	 * email can be turned off in the settings.
+	 *
+	 * @param WC_Order    $order         Order of the row.
+	 * @param Fulfillment $fulfillment   Saved fulfillment.
+	 * @param bool        $was_fulfilled Whether the fulfillment was fulfilled before this row.
+	 * @param int         $row_number    Physical record number, for the log.
+	 * @return bool Whether the notification action ran without an error.
+	 */
+	private function notify_customer( WC_Order $order, Fulfillment $fulfillment, bool $was_fulfilled, int $row_number ): bool {
+		$hook_depth = count( $GLOBALS['wp_current_filter'] );
+		try {
+			if ( $was_fulfilled ) {
+				/**
+				 * This action is documented in src/Admin/Features/Fulfillments/OrderFulfillmentsRestController.php.
+				 *
+				 * @since 10.1.0
+				 * @since 10.8.0 Added $customer_note parameter.
+				 */
+				do_action( 'woocommerce_fulfillment_updated_notification', $order->get_id(), $fulfillment, $order, '' );
+			} else {
+				/**
+				 * This action is documented in src/Admin/Features/Fulfillments/OrderFulfillmentsRestController.php.
+				 *
+				 * @since 10.1.0
+				 */
+				do_action( 'woocommerce_fulfillment_created_notification', $order->get_id(), $fulfillment, $order );
+			}
+			return true;
+		} catch ( \Throwable $e ) {
+			self::restore_filter_stack( $hook_depth );
+			// The listener may have changed the cached fulfillment, so the next row reads it again.
+			unset( $this->fulfillments_cache[ $order->get_id() ] );
+			wc_get_logger()->error(
+				sprintf( 'Fulfillments import could not notify the customer for row %1$d of order %2$d: %3$s', $row_number, $order->get_id(), $e->getMessage() ),
+				array( 'source' => 'fulfillments-importer' )
+			);
+			return false;
+		}
+	}
+
+	/**
+	 * Take the hooks a throwing listener left on the filter stack back off it.
+	 *
+	 * Otherwise doing_action() stays true for them, and the data store skips its
+	 * after-save actions, which add order notes and update the order status, for later rows.
+	 *
+	 * @param int $depth Stack depth before the call that threw.
+	 */
+	private static function restore_filter_stack( int $depth ): void {
+		global $wp_current_filter;
+		array_splice( $wp_current_filter, $depth );
+	}
+
+	/**
+	 * Build a failed row result.
+	 *
+	 * @param string $code     Machine-readable failure code.
+	 * @param string $message  Plain text that can hold raw CSV values; escape it on output.
+	 * @param int    $order_id Resolved order ID, or 0 when the order is not known.
+	 * @return array<string, mixed>
+	 */
+	private static function fail( string $code, string $message, int $order_id = 0 ): array {
+		$result = array(
+			'status'  => self::STATUS_FAILED,
+			'code'    => $code,
+			'message' => $message,
+		);
+		if ( $order_id > 0 ) {
+			$result['order_id'] = $order_id;
+		}
+		return $result;
+	}
+
+	/**
+	 * Cut a CSV value echoed in a row result, since the results are stored with the session.
+	 *
+	 * @param string $value CSV value.
+	 * @return string The value, or its first 100 characters followed by "...".
+	 */
+	private static function clip( string $value ): string {
+		return mb_strlen( $value ) > 100 ? mb_substr( $value, 0, 100 ) . '...' : $value;
+	}
+
+	/**
+	 * Read a mapped cell of a row.
+	 *
+	 * @param array<int, string> $cells      Trimmed cells.
+	 * @param array<string, int> $header_map Canonical column key => CSV column index.
+	 * @param string             $column     Canonical column key.
+	 * @return string Empty when the column is not mapped or the row has no such cell.
+	 */
+	private static function get_field( array $cells, array $header_map, string $column ): string {
+		return isset( $header_map[ $column ] ) ? (string) ( $cells[ $header_map[ $column ] ] ?? '' ) : '';
+	}
+
+	/**
+	 * Keep a tracking URL only when it is an http or https URL.
+	 *
+	 * The URL is shown as a link in the admin and in customer emails. esc_url_raw() adds
+	 * "http://" to a cell without a scheme, so the cell itself must start with one.
+	 *
+	 * @param string $url URL cell.
+	 * @return string Sanitized URL, or empty when it is not allowed.
+	 */
+	private function sanitize_tracking_url( string $url ): string {
+		$lower = strtolower( $url );
+		if ( ! str_starts_with( $lower, 'http://' ) && ! str_starts_with( $lower, 'https://' ) ) {
+			return '';
+		}
+		$url = esc_url_raw( $url, array( 'http', 'https' ) );
+		return '' !== (string) wp_parse_url( $url, PHP_URL_HOST ) ? $url : '';
+	}
+
+	/**
+	 * Map a provider cell to a known provider key, matching the key or the name without case.
+	 *
+	 * @param string $cell Provider cell.
+	 * @return string Provider key, or empty when the provider is not known.
+	 */
+	private function known_provider_key( string $cell ): string {
+		if ( null === $this->provider_keys ) {
+			// Kept unset until the list is built, so a lookup that throws runs again for the next row.
+			$keys = array();
+			foreach ( FulfillmentUtils::get_shipping_providers() as $key => $provider ) {
+				$keys[ wc_strtolower( $provider->get_name() ) ] = (string) $key;
+				$keys[ wc_strtolower( (string) $key ) ]         = (string) $key;
+			}
+			$this->provider_keys = $keys;
+		}
+		return $this->provider_keys[ wc_strtolower( $cell ) ] ?? '';
+	}
+
+	/**
+	 * Load the orders a chunk names by ID in one query.
+	 *
+	 * The import run builds a new importer for each request, so without this every row
+	 * would load its order on its own. The resolve-order filter still runs once per distinct
+	 * order number.
+	 *
+	 * @param array<int, array{row_number:int, cells:array<int, string>}> $rows       Rows of the chunk.
+	 * @param array<string, int>                                          $header_map Canonical column key => CSV column index.
+	 */
+	private function prime_orders( array $rows, array $header_map ): void {
+		$ids = array();
+		foreach ( $rows as $row ) {
+			$order_number = self::get_field( $row['cells'], $header_map, self::COL_ORDER_NUMBER );
+			if ( ctype_digit( $order_number ) ) {
+				$ids[] = (int) $order_number;
+			}
+		}
+		$ids = array_values( array_unique( $ids ) );
+		if ( array() === $ids ) {
+			return;
+		}
+
+		// post__in is the ID argument both order data stores understand. The default status
+		// list includes checkout drafts, which are carts that were never placed.
+		$orders = wc_get_orders(
+			array(
+				'post__in' => $ids,
+				'limit'    => count( $ids ),
+				'status'   => array_diff( array_keys( wc_get_order_statuses() ), array( 'wc-' . OrderStatus::CHECKOUT_DRAFT ) ),
+			)
+		);
+		// The result passes through the woocommerce_order_query filter, so it is checked.
+		foreach ( is_array( $orders ) ? $orders : array() as $order ) {
+			if ( $order instanceof WC_Order ) {
+				$this->primed_orders[ $order->get_id() ] = $order;
+			}
+		}
+	}
+
+	/**
+	 * Resolve an order number cell to an order.
+	 *
+	 * A number is looked up among the orders prime_orders() loaded by ID: orders with a registered
+	 * order status other than checkout-draft, so trashed and checkout-draft orders are not found. The
+	 * filter then decides, so a store with its own order numbers can map them. The result is cached
+	 * on the importer.
+	 *
+	 * @param string $order_number Order number cell.
+	 * @return WC_Order|null
+	 */
+	private function resolve_order( string $order_number ): ?WC_Order {
+		if ( array_key_exists( $order_number, $this->order_cache ) ) {
+			return $this->order_cache[ $order_number ];
+		}
+
+		$order = null;
+		if ( ctype_digit( $order_number ) ) {
+			$order = $this->primed_orders[ (int) $order_number ] ?? null;
+		}
+
+		/**
+		 * Filter the order a fulfillments CSV row is imported into.
+		 *
+		 * The default looks up a numeric order number as an order ID. Return a WC_Order to
+		 * map custom order numbers, or null when the order cannot be found. Any other value
+		 * fails the row.
+		 *
+		 * @since 11.4.0
+		 *
+		 * @param WC_Order|null $order        Order found by ID, or null.
+		 * @param string        $order_number Order number cell from the CSV.
+		 */
+		$order = apply_filters( 'woocommerce_fulfillments_csv_importer_resolve_order', $order instanceof WC_Order ? $order : null, $order_number );
+
+		$this->order_cache[ $order_number ] = $order instanceof WC_Order ? $order : null;
+		return $this->order_cache[ $order_number ];
+	}
+
+	/**
+	 * Find the order's fulfillment that is not deleted and has this tracking number, ignoring case.
+	 *
+	 * @param int    $order_id        Order ID.
+	 * @param string $tracking_number Tracking number.
+	 * @return Fulfillment|null
+	 *
+	 * @throws \RuntimeException When the fulfillments cannot be read.
+	 */
+	private function find_existing_fulfillment( int $order_id, string $tracking_number ): ?Fulfillment {
+		if ( ! isset( $this->fulfillments_cache[ $order_id ] ) ) {
+			global $wpdb;
+			/**
+			 * Fulfillments data store.
+			 *
+			 * @var FulfillmentsDataStore $store
+			 */
+			$store        = WC_Data_Store::load( 'order-fulfillment' );
+			$fulfillments = $store->read_fulfillments( WC_Order::class, (string) $order_id );
+			// A failed query reads as no fulfillments, which would turn an update into a duplicate.
+			if ( '' !== $wpdb->last_error ) {
+				wc_get_logger()->error(
+					sprintf( 'Fulfillments import could not read the fulfillments of order %1$d: %2$s', $order_id, $wpdb->last_error ),
+					array( 'source' => 'fulfillments-importer' )
+				);
+				// Not cached, so the next row of this order reads again.
+				throw new \RuntimeException( 'fulfillments_read_failed' );
+			}
+			$this->fulfillments_cache[ $order_id ] = $fulfillments;
+		}
+
+		$needle = strtolower( $tracking_number );
+		foreach ( $this->fulfillments_cache[ $order_id ] as $fulfillment ) {
+			if ( $fulfillment instanceof Fulfillment && strtolower( (string) $fulfillment->get_tracking_number() ) === $needle ) {
+				return $fulfillment;
+			}
+		}
+		return null;
+	}
+
+	/**
+	 * Parse an items cell into fulfillment items.
+	 *
+	 * Entries are separated by "|" or ";" and are either "<order item ID>:<qty>" or
+	 * "sku:<SKU>:<qty>"; empty entries are skipped. Quantities of a repeated item are
+	 * added up before they are checked against the quantity left to fulfill.
+	 *
+	 * @param string          $cell    Items cell, not empty.
+	 * @param WC_Order        $order   Order of the row.
+	 * @param array<int, int> $pending Order item ID => quantity left to fulfill.
+	 * @return array<int, array{item_id:int, qty:int}>|string Items, or a message saying why the cell is invalid.
+	 */
+	private function parse_items( string $cell, WC_Order $order, array $pending ) {
+		$line_items = $order->get_items( 'line_item' );
+		$by_sku     = null;
+		$totals     = array();
+		foreach ( explode( '|', str_replace( ';', '|', $cell ) ) as $entry ) {
+			$entry = trim( $entry );
+			if ( '' === $entry ) {
+				continue;
+			}
+			$parts  = array_map( 'trim', explode( ':', $entry ) );
+			$is_sku = 'sku' === strtolower( $parts[0] );
+			if ( count( $parts ) !== ( $is_sku ? 3 : 2 ) ) {
+				/* translators: %s: one entry of the items cell. */
+				return sprintf( __( 'Invalid items entry: %s.', 'woocommerce' ), self::clip( $entry ) );
+			}
+			if ( $is_sku ) {
+				// Built on first use, since it loads the product of every line item.
+				$by_sku = $by_sku ?? $this->index_items_by_sku( $line_items );
+				$item   = $by_sku[ wc_strtolower( $parts[1] ) ] ?? null;
+				if ( false === $item ) {
+					/* translators: %s: SKU from the CSV. */
+					return sprintf( __( 'SKU %s matches more than one item of this order. Use the item ID instead.', 'woocommerce' ), self::clip( $parts[1] ) );
+				}
+				if ( null === $item ) {
+					/* translators: %s: SKU from the CSV. */
+					return sprintf( __( 'SKU %s was not found on the order.', 'woocommerce' ), self::clip( $parts[1] ) );
+				}
+			} else {
+				$item = ctype_digit( $parts[0] ) ? ( $line_items[ (int) $parts[0] ] ?? null ) : null;
+				if ( null === $item ) {
+					/* translators: %s: order item ID from the CSV. */
+					return sprintf( __( 'Item ID %s is not part of this order.', 'woocommerce' ), self::clip( $parts[0] ) );
+				}
+			}
+
+			$qty = (string) end( $parts );
+			if ( ! ctype_digit( $qty ) || 0 === (int) $qty ) {
+				return __( 'Item quantity must be a positive integer.', 'woocommerce' );
+			}
+			$totals[ $item->get_id() ] = ( $totals[ $item->get_id() ] ?? 0 ) + (int) $qty;
+		}
+
+		if ( array() === $totals ) {
+			return __( 'The items cell has no item entries.', 'woocommerce' );
+		}
+
+		$items = array();
+		foreach ( $totals as $item_id => $qty ) {
+			$left = $pending[ $item_id ] ?? 0;
+			if ( $qty > $left ) {
+				/* translators: 1: quantity from the CSV, 2: quantity of the item not fulfilled yet. */
+				return sprintf( __( 'Item quantity %1$d exceeds the quantity left to fulfill %2$d.', 'woocommerce' ), $qty, $left );
+			}
+			$items[] = array(
+				'item_id' => (int) $item_id,
+				'qty'     => $qty,
+			);
+		}
+		return $items;
+	}
+
+	/**
+	 * Index line items by lowercase SKU.
+	 *
+	 * @param array<int|string, \WC_Order_Item> $line_items Line items of the order.
+	 * @return array<string, \WC_Order_Item|false> False for a SKU shared by more than one line item.
+	 */
+	private function index_items_by_sku( array $line_items ): array {
+		$by_sku = array();
+		foreach ( $line_items as $item ) {
+			$product = $item instanceof \WC_Order_Item_Product ? $item->get_product() : null;
+			$sku     = $product instanceof \WC_Product ? wc_strtolower( (string) $product->get_sku() ) : '';
+			if ( '' !== $sku ) {
+				$by_sku[ $sku ] = isset( $by_sku[ $sku ] ) ? false : $item;
+			}
+		}
+		return $by_sku;
+	}
+
+	/**
+	 * Quantities left to fulfill per order item, after refunds and the order's other fulfillments.
+	 *
+	 * @param WC_Order         $order    Order of the row.
+	 * @param Fulfillment|null $existing Fulfillment the row updates; its own items count as not fulfilled.
+	 * @return array<int, int> Order item ID => quantity.
+	 */
+	private function pending_items( WC_Order $order, ?Fulfillment $existing ): array {
+		$others = array_filter(
+			$this->fulfillments_cache[ $order->get_id() ] ?? array(),
+			static function ( $fulfillment ) use ( $existing ) {
+				return $fulfillment !== $existing;
+			}
+		);
+		return array_map( 'intval', array_column( FulfillmentUtils::get_pending_items( $order, $others ), 'qty', 'item_id' ) );
+	}
+
 	/**
 	 * Read one window of data rows from a handle already past its BOM.
 	 *
diff --git a/plugins/woocommerce/src/Admin/Features/Fulfillments/Importer/ImportSession.php b/plugins/woocommerce/src/Admin/Features/Fulfillments/Importer/ImportSession.php
index ec627b99637..ec14fc4f212 100644
--- a/plugins/woocommerce/src/Admin/Features/Fulfillments/Importer/ImportSession.php
+++ b/plugins/woocommerce/src/Admin/Features/Fulfillments/Importer/ImportSession.php
@@ -16,9 +16,9 @@ defined( 'ABSPATH' ) || exit;
  * Per-user import session stored in a transient.
  *
  * The prepare endpoint creates it with the staged file path, attachment ID, delimiter,
- * headers and row total, and schedules the cleanup of the staged file. The progress
- * fields (processed, byte_offset, mapping, counts, seen_tracking_pairs) are stored here
- * for the import run that lands next. One session is active per user at a time.
+ * headers and row total, and schedules the cleanup of the staged file. The import run
+ * freezes its mapping here and records each chunk's progress (processed, byte_offset,
+ * counts, seen_tracking_pairs, last chunk). One session is active per user at a time.
  *
  * @internal
  * @since 11.4.0
@@ -669,6 +669,43 @@ final class ImportSession {
 		return $out;
 	}

+	/**
+	 * Freeze the mapping and run options so every chunk imports under the same rules.
+	 *
+	 * Only the first call stores the values; later calls keep them. The stored payload is read
+	 * first and this copy takes it over, so a copy loaded before another request froze the
+	 * settings or recorded a chunk cannot write over them. That narrows the window for two
+	 * requests freezing at once; the caller's lock closes it.
+	 *
+	 * @since 11.4.0
+	 *
+	 * @param array<int, string> $mapping CSV column index => canonical column key.
+	 * @param bool               $notify  Whether to fire customer notifications.
+	 * @param bool               $update  Whether to update existing fulfillments on tracking-number match.
+	 * @return bool False when the session is gone or the settings could not be stored.
+	 */
+	public function freeze_run_settings( array $mapping, bool $notify, bool $update ): bool {
+		if ( null !== $this->frozen_mapping() ) {
+			return true;
+		}
+		$stored = get_transient( self::PREFIX . $this->user_id . '_' . $this->token );
+		if ( ! is_array( $stored ) ) {
+			return false;
+		}
+		$this->data = $stored;
+		if ( null !== $this->frozen_mapping() ) {
+			return true;
+		}
+		$this->data['mapping']         = $mapping;
+		$this->data['notify_customer'] = $notify;
+		$this->data['update_existing'] = $update;
+		if ( $this->persist() ) {
+			return true;
+		}
+		$this->data = $stored;
+		return false;
+	}
+
 	/**
 	 * Byte offset in the CSV reached by the import run.
 	 *
@@ -680,6 +717,92 @@ final class ImportSession {
 		return (int) ( $this->data['byte_offset'] ?? 0 );
 	}

+	/**
+	 * Physical record number of the row at byte_offset(), passed back to the reader on resume.
+	 *
+	 * @since 11.4.0
+	 *
+	 * @return int 0 until a chunk is recorded.
+	 */
+	public function next_record_number(): int {
+		return (int) ( $this->data['next_record_number'] ?? 0 );
+	}
+
+	/**
+	 * The most recently recorded chunk: its offset, per-row results and end-of-file flag.
+	 *
+	 * Lets a caller answer a replay of that chunk without importing its rows again.
+	 *
+	 * @since 11.4.0
+	 *
+	 * @return array{offset:int, rows:array<int, array<string, mixed>>, eof:bool}|null Null until a chunk is recorded.
+	 */
+	public function last_chunk(): ?array {
+		$chunk = $this->data['last_chunk'] ?? null;
+		if ( ! is_array( $chunk ) ) {
+			return null;
+		}
+		return array(
+			'offset' => (int) ( $chunk['offset'] ?? 0 ),
+			'rows'   => is_array( $chunk['rows'] ?? null ) ? $chunk['rows'] : array(),
+			'eof'    => ! empty( $chunk['eof'] ),
+		);
+	}
+
+	/**
+	 * Record a chunk returned by FulfillmentsCsvImporter::import_chunk() and persist the session.
+	 *
+	 * Only a chunk that starts at the recorded progress, in memory and in the stored payload,
+	 * is accepted, so a replayed or out-of-order chunk never adds its counts twice. This
+	 * protects the counts only: the caller compares the offset before importing the rows.
+	 * Re-reading the payload narrows the window for two requests recording the same chunk;
+	 * the caller's lock closes it. The chunk is written on top of the stored payload, so
+	 * settings another copy froze are kept. The dedupe set and the resume position are
+	 * replaced, and only this chunk's rows are kept, which bounds the payload.
+	 *
+	 * @since 11.4.0
+	 *
+	 * @param int                  $offset Data rows processed before this chunk; must equal processed().
+	 * @param array<string, mixed> $chunk  Result of import_chunk() without an error.
+	 * @return bool False for an error result, an offset that is not the recorded progress, a
+	 *              session that is gone, or a payload that could not be stored.
+	 */
+	public function record_chunk( int $offset, array $chunk ): bool {
+		if ( isset( $chunk['error'] ) || $offset !== $this->processed() ) {
+			return false;
+		}
+		$stored = get_transient( self::PREFIX . $this->user_id . '_' . $this->token );
+		if ( ! is_array( $stored ) || (int) ( $stored['processed'] ?? 0 ) !== $offset ) {
+			return false;
+		}
+		// Build on the stored payload, which may hold settings frozen by a copy loaded later.
+		$this->data = $stored;
+
+		$counts = $this->counts();
+		foreach ( array_keys( $counts ) as $key ) {
+			$counts[ $key ] += (int) ( $chunk['counts'][ $key ] ?? 0 );
+		}
+		$rows = is_array( $chunk['rows'] ?? null ) ? array_values( $chunk['rows'] ) : array();
+		$seen = $chunk['seen_tracking_pairs'] ?? array();
+
+		$this->data['processed']           = $offset + max( 0, (int) ( $chunk['consumed'] ?? 0 ) );
+		$this->data['counts']              = $counts;
+		$this->data['seen_tracking_pairs'] = is_array( $seen ) ? $seen : array();
+		$this->data['byte_offset']         = max( 0, (int) ( $chunk['byte_offset'] ?? 0 ) );
+		$this->data['next_record_number']  = max( 0, (int) ( $chunk['next_record_number'] ?? 0 ) );
+		$this->data['last_chunk']          = array(
+			'offset' => $offset,
+			'rows'   => $rows,
+			'eof'    => ! empty( $chunk['eof'] ),
+		);
+
+		if ( $this->persist() ) {
+			return true;
+		}
+		$this->data = $stored;
+		return false;
+	}
+
 	/**
 	 * Cumulative result counts recorded by the import run.
 	 *
@@ -690,18 +813,18 @@ final class ImportSession {
 	public function counts(): array {
 		$counts = is_array( $this->data['counts'] ?? null ) ? $this->data['counts'] : array();
 		return array(
-			'created'  => (int) ( $counts['created'] ?? 0 ),
-			'updated'  => (int) ( $counts['updated'] ?? 0 ),
-			'skipped'  => (int) ( $counts['skipped'] ?? 0 ),
-			'failed'   => (int) ( $counts['failed'] ?? 0 ),
-			'notified' => (int) ( $counts['notified'] ?? 0 ),
+			FulfillmentsCsvImporter::STATUS_CREATED => (int) ( $counts[ FulfillmentsCsvImporter::STATUS_CREATED ] ?? 0 ),
+			FulfillmentsCsvImporter::STATUS_UPDATED => (int) ( $counts[ FulfillmentsCsvImporter::STATUS_UPDATED ] ?? 0 ),
+			FulfillmentsCsvImporter::STATUS_SKIPPED => (int) ( $counts[ FulfillmentsCsvImporter::STATUS_SKIPPED ] ?? 0 ),
+			FulfillmentsCsvImporter::STATUS_FAILED  => (int) ( $counts[ FulfillmentsCsvImporter::STATUS_FAILED ] ?? 0 ),
+			'notified'                              => (int) ( $counts['notified'] ?? 0 ),
 		);
 	}

 	/**
 	 * The stored counts plus an empty rows list, in the shape the import run reports.
 	 *
-	 * Per-row results are not persisted, so rows is always empty here.
+	 * Rows are left empty here; the rows of the last recorded chunk are in last_chunk().
 	 *
 	 * @since 11.4.0
 	 *
diff --git a/plugins/woocommerce/tests/php/src/Admin/Features/Fulfillments/Importer/FulfillmentsCsvImporterTest.php b/plugins/woocommerce/tests/php/src/Admin/Features/Fulfillments/Importer/FulfillmentsCsvImporterTest.php
index d2f996cdcf0..611586ac9d2 100644
--- a/plugins/woocommerce/tests/php/src/Admin/Features/Fulfillments/Importer/FulfillmentsCsvImporterTest.php
+++ b/plugins/woocommerce/tests/php/src/Admin/Features/Fulfillments/Importer/FulfillmentsCsvImporterTest.php
@@ -4,14 +4,31 @@ namespace Automattic\WooCommerce\Tests\Admin\Features\Fulfillments\Importer;

 require_once __DIR__ . '/FulfillmentsCsvReadTracker.php';

+use Automattic\WooCommerce\Admin\Features\Fulfillments\Fulfillment;
+use Automattic\WooCommerce\Admin\Features\Fulfillments\FulfillmentException;
 use Automattic\WooCommerce\Admin\Features\Fulfillments\Importer\FulfillmentsCsvImporter;
+use Automattic\WooCommerce\Admin\Features\Fulfillments\Importer\ImportSession;
+use Automattic\WooCommerce\RestApi\UnitTests\Helpers\OrderHelper;
 use Automattic\WooCommerce\Tests\Admin\Features\Fulfillments\Helpers\FulfillmentsHelper;
+use WC_Data_Store;
+use WC_Order;

 /**
  * Tests for the Fulfillments CSV importer service.
  */
 class FulfillmentsCsvImporterTest extends \WC_Unit_Test_Case {

+	/**
+	 * Column mapping the import tests use; their CSVs list the columns in this order.
+	 */
+	private const IMPORT_MAPPING = array(
+		0 => FulfillmentsCsvImporter::COL_ORDER_NUMBER,
+		1 => FulfillmentsCsvImporter::COL_TRACKING_NUMBER,
+		2 => FulfillmentsCsvImporter::COL_PROVIDER,
+		3 => FulfillmentsCsvImporter::COL_TRACKING_URL,
+		4 => FulfillmentsCsvImporter::COL_ITEMS,
+	);
+
 	/**
 	 * Paths to temporary CSV files created by tests; cleaned up in tearDown.
 	 *
@@ -64,6 +81,62 @@ class FulfillmentsCsvImporterTest extends \WC_Unit_Test_Case {
 		return $path;
 	}

+	/**
+	 * Import a CSV the way the import run does: a new importer per chunk, each resuming from the last result.
+	 *
+	 * @param string               $csv     CSV content with its columns in the order of IMPORT_MAPPING.
+	 * @param array<string, mixed> $options Importer options.
+	 * @param int                  $limit   Data rows per chunk.
+	 * @return array{counts: array<string, int>, rows: array<int, array<string, mixed>>}
+	 */
+	private function import_csv( string $csv, array $options = array(), int $limit = 200 ): array {
+		$file   = $this->make_csv( $csv );
+		$state  = array();
+		$counts = array_fill_keys( array( FulfillmentsCsvImporter::STATUS_CREATED, FulfillmentsCsvImporter::STATUS_UPDATED, FulfillmentsCsvImporter::STATUS_SKIPPED, FulfillmentsCsvImporter::STATUS_FAILED, 'notified' ), 0 );
+		$rows   = array();
+		$chunks = 0;
+		do {
+			$chunk = ( new FulfillmentsCsvImporter( $file, $options ) )->import_chunk( $limit, self::IMPORT_MAPPING, $state );
+			$this->assertArrayNotHasKey( 'error', $chunk );
+			foreach ( $chunk['counts'] as $key => $count ) {
+				$counts[ $key ] += $count;
+			}
+			$rows  = array_merge( $rows, $chunk['rows'] );
+			$state = $chunk;
+			++$chunks;
+		} while ( ! $chunk['eof'] && $chunks < 20 );
+
+		return array(
+			'counts' => $counts,
+			'rows'   => $rows,
+		);
+	}
+
+	/**
+	 * Assert fulfillment items one field at a time.
+	 *
+	 * @param array<int, int>                  $expected Order item ID => quantity, in the stored order.
+	 * @param array<int, array<string, mixed>> $items    Fulfillment items.
+	 * @param string                           $message  Assertion message.
+	 */
+	private function assert_items( array $expected, array $items, string $message = '' ): void {
+		$this->assertCount( count( $expected ), $items, $message );
+		foreach ( array_keys( $expected ) as $index => $item_id ) {
+			$this->assertSame( $item_id, $items[ $index ]['item_id'], $message );
+			$this->assertSame( $expected[ $item_id ], $items[ $index ]['qty'], $message );
+		}
+	}
+
+	/**
+	 * Fulfillments of an order that are not deleted.
+	 *
+	 * @param WC_Order $order Order.
+	 * @return array<int, Fulfillment>
+	 */
+	private function fulfillments_of( WC_Order $order ): array {
+		return WC_Data_Store::load( 'order-fulfillment' )->read_fulfillments( WC_Order::class, (string) $order->get_id() );
+	}
+
 	/**
 	 * @testdox Header aliases (e.g. "Tracking" / "Carrier") are normalized to the canonical columns.
 	 */
@@ -931,4 +1004,1041 @@ class FulfillmentsCsvImporterTest extends \WC_Unit_Test_Case {
 		$this->assertSame( array( '1043', '1Z998', 'usps' ), $read['rows'][1]['cells'], 'Whitespace inside a quoted cell and a leading tab are trimmed too' );
 		$this->assertSame( $parsed['headers'], $read['headers'], 'Both paths must return the same trimmed headers' );
 	}
+
+	/**
+	 * @testdox resolve_chunk_size() keeps the filtered size between 1 and 1000, and at most 25 while notifying.
+	 * @testWith [null, false, 200]
+	 *           [50, false, 50]
+	 *           ["75", false, 75]
+	 *           [0, false, 200]
+	 *           ["junk", false, 200]
+	 *           [5000, false, 1000]
+	 *           [[500], false, 200]
+	 *           [null, true, 25]
+	 *           [10, true, 10]
+	 *           [500, true, 25]
+	 *
+	 * @param mixed $filtered Value the filter returns; null leaves the default.
+	 * @param bool  $notify   Whether the import notifies customers.
+	 * @param int   $expected Expected chunk size.
+	 */
+	public function test_resolve_chunk_size_clamps_the_filtered_value( $filtered, bool $notify, int $expected ): void {
+		$received = array();
+		add_filter(
+			'woocommerce_fulfillments_csv_importer_chunk_size',
+			function ( $size, $notify_customer ) use ( $filtered, &$received ) {
+				$received = array( $size, $notify_customer );
+				return $filtered ?? $size;
+			},
+			10,
+			2
+		);
+
+		$this->assertSame( $expected, FulfillmentsCsvImporter::resolve_chunk_size( $notify ) );
+		$this->assertSame( array( 200, $notify ), $received, 'The filter receives the default size and the notify flag' );
+	}
+
+	/**
+	 * @testdox A valid row creates a fulfilled fulfillment covering every order item at its ordered quantity.
+	 */
+	public function test_valid_row_creates_a_fulfilled_fulfillment_with_every_order_item(): void {
+		$order = OrderHelper::create_order();
+		$id    = $order->get_id();
+		$zero  = new \WC_Order_Item_Product();
+		$zero->set_quantity( 0 );
+		$order->add_item( $zero );
+		$order->save();
+
+		$result = $this->import_csv( "order_number,tracking_number,shipment_provider,tracking_url\n{$id},TRK-1,ups,https://example.com/t/<b>TRK-1\n" );
+
+		$this->assertSame( 1, $result['counts'][ FulfillmentsCsvImporter::STATUS_CREATED ] );
+		$fulfillments = $this->fulfillments_of( $order );
+		$this->assertCount( 1, $fulfillments );
+		$fulfillment = $fulfillments[0];
+		$row         = $result['rows'][0];
+		foreach ( array( 'row', 'order_number', 'status', 'message', 'order_id', 'fulfillment_id', 'notified' ) as $key ) {
+			$this->assertArrayHasKey( $key, $row, 'The import client reads this key' );
+		}
+		$this->assertSame( 2, $row['row'] );
+		$this->assertSame( FulfillmentsCsvImporter::STATUS_CREATED, $row['status'] );
+		$this->assertSame( $id, $row['order_id'] );
+		$this->assertSame( $fulfillment->get_id(), $row['fulfillment_id'] );
+		$this->assertFalse( $row['notified'] );
+		$this->assertTrue( $fulfillment->get_is_fulfilled() );
+		$this->assertSame( 'TRK-1', $fulfillment->get_tracking_number() );
+		$this->assertSame( 'ups', $fulfillment->get_shipment_provider() );
+		$this->assertSame( 'https://example.com/t/bTRK-1', $fulfillment->get_tracking_url(), 'The URL is sanitized before it is stored' );
+		$this->assert_items( array( current( $order->get_items() )->get_id() => 4 ), $fulfillment->get_items(), 'A row without an items cell fulfills every line item with a quantity' );
+	}
+
+	/**
+	 * @testdox Each invalid row fails with its own code while the valid rows of the file still import.
+	 */
+	public function test_invalid_rows_fail_with_a_code_while_the_rest_imports(): void {
+		$order    = OrderHelper::create_order();
+		$id       = $order->get_id();
+		$no_items = wc_create_order()->get_id();
+		$trashed  = OrderHelper::create_order();
+		$trashed->delete( false );
+		$draft = OrderHelper::create_order();
+		$draft->set_status( 'checkout-draft' );
+		$draft->save();
+		add_filter(
+			'woocommerce_fulfillment_before_create',
+			function ( $fulfillment ) {
+				if ( 'TRK-BLOCKED' === $fulfillment->get_tracking_number() ) {
+					throw new FulfillmentException( 'Blocked by an extension.' );
+				}
+				if ( 'TRK-CRASH' === $fulfillment->get_tracking_number() ) {
+					throw new \RuntimeException( 'Database gone away.' );
+				}
+				return $fulfillment;
+			}
+		);
+
+		$result = $this->import_csv(
+			"order_number,tracking_number,shipment_provider,tracking_url\n"
+			. ",TRK-A,ups,\n{$id},,ups,\n{$id},TRK-B,,\n999999999,TRK-C,ups,\nINV-1,TRK-D,ups,\n"
+			. "{$id},TRK-E,ups,javascript:alert(1)\n{$id},TRK-F,ups,//example.com/t\n{$id},TRK-G,ups,/wp-admin/\n{$id},TRK-H,ups,ftp://example.com/t\n"
+			. "{$no_items},TRK-I,ups,\n{$id},TRK-BLOCKED,ups,\n{$id},TRK-CRASH,ups,\n"
+			. "{$trashed->get_id()},TRK-T,ups,\n{$draft->get_id()},TRK-DR,ups,\n{$id}x,TRK-X,ups,\n{$id},TRK-OK,ups,http://example.com/t\n"
+		);
+
+		$this->assertSame(
+			array( FulfillmentsCsvImporter::CODE_MISSING_ORDER_NUMBER, FulfillmentsCsvImporter::CODE_MISSING_TRACKING_NUMBER, FulfillmentsCsvImporter::CODE_MISSING_PROVIDER, FulfillmentsCsvImporter::CODE_ORDER_NOT_FOUND, FulfillmentsCsvImporter::CODE_ORDER_NOT_FOUND, FulfillmentsCsvImporter::CODE_INVALID_TRACKING_URL, FulfillmentsCsvImporter::CODE_INVALID_TRACKING_URL, FulfillmentsCsvImporter::CODE_INVALID_TRACKING_URL, FulfillmentsCsvImporter::CODE_INVALID_TRACKING_URL, FulfillmentsCsvImporter::CODE_NO_ITEMS, FulfillmentsCsvImporter::CODE_SAVE_FAILED, FulfillmentsCsvImporter::CODE_SAVE_FAILED, FulfillmentsCsvImporter::CODE_ORDER_NOT_FOUND, FulfillmentsCsvImporter::CODE_ORDER_NOT_FOUND, FulfillmentsCsvImporter::CODE_ORDER_NOT_FOUND, null ),
+			array_map(
+				static function ( $row ) {
+					return $row['code'] ?? null;
+				},
+				$result['rows']
+			)
+		);
+		$this->assertSame( 1, $result['counts'][ FulfillmentsCsvImporter::STATUS_CREATED ] );
+		$this->assertSame( 15, $result['counts'][ FulfillmentsCsvImporter::STATUS_FAILED ] );
+		$this->assertSame( range( 2, 17 ), array_column( $result['rows'], 'row' ) );
+		foreach ( array( 'row', 'order_number', 'status', 'code', 'message' ) as $key ) {
+			$this->assertArrayHasKey( $key, $result['rows'][1] );
+			$this->assertArrayHasKey( $key, $result['rows'][9] );
+		}
+		$this->assertArrayNotHasKey( 'order_id', $result['rows'][1], 'A row that fails before its order resolves has no order_id' );
+		$this->assertSame( (string) $id, $result['rows'][1]['order_number'] );
+		$this->assertSame( $no_items, $result['rows'][9]['order_id'] );
+		$this->assertSame( 'Blocked by an extension.', $result['rows'][10]['message'], 'An extension message from a blocked save reaches the merchant' );
+		$this->assertSame( 'Could not save the fulfillment.', $result['rows'][11]['message'], 'Other save errors are not shown to the merchant' );
+		$this->assertSame( 'INV-1', $result['rows'][4]['order_number'], 'A failed row still names the order number from the file' );
+		$fulfillments = $this->fulfillments_of( $order );
+		$this->assertCount( 1, $fulfillments );
+		$this->assertSame( 'http://example.com/t', $fulfillments[0]->get_tracking_url() );
+	}
+
+	/**
+	 * @testdox CSV values echoed in a row result are cut to 100 characters.
+	 */
+	public function test_echoed_csv_values_are_shortened(): void {
+		$order = OrderHelper::create_order();
+		$long  = str_repeat( 'x', 101 );
+		$short = str_repeat( 'x', 100 ) . '...';
+		$fits  = str_repeat( 'y', 100 );
+
+		$result = $this->import_csv( "order_number,tracking_number,shipment_provider,tracking_url,items\n{$long},TRK-1,ups,,\n{$order->get_id()},TRK-2,ups,,{$long}\n{$fits},TRK-3,ups,,\n" );
+
+		$this->assertSame( $short, $result['rows'][0]['order_number'] );
+		$this->assertSame( "Order not found for order number \"{$short}\".", $result['rows'][0]['message'] );
+		$this->assertSame( "Invalid items entry: {$short}.", $result['rows'][1]['message'] );
+		$this->assertSame( $fits, $result['rows'][2]['order_number'] );
+	}
+
+	/**
+	 * @testdox A tracking URL must start with http:// or https:// and keep a host after sanitizing.
+	 * @testWith ["N/A", null]
+	 *           ["http:example.com", null]
+	 *           ["https:/example.com", null]
+	 *           ["http:///path", null]
+	 *           ["HTTPS://Host/x", "https://Host/x"]
+	 *
+	 * @param string      $cell   Tracking URL cell.
+	 * @param string|null $stored Expected stored URL, or null when the row fails.
+	 */
+	public function test_tracking_url_needs_an_http_scheme_and_a_host( string $cell, ?string $stored ): void {
+		$order = OrderHelper::create_order();
+
+		$result = $this->import_csv( "order_number,tracking_number,shipment_provider,tracking_url\n{$order->get_id()},TRK-1,ups,{$cell}\n" );
+
+		$this->assertSame( null === $stored ? FulfillmentsCsvImporter::CODE_INVALID_TRACKING_URL : null, $result['rows'][0]['code'] ?? null );
+		$this->assertSame( $stored, null === $stored ? null : $this->fulfillments_of( $order )[0]->get_tracking_url() );
+	}
+
+	/**
+	 * @testdox A provider cell maps to a known provider by key or name ignoring case, and anything else is stored as a custom provider.
+	 * @testWith ["UPS", "ups", ""]
+	 *           ["royal mail", "royal-mail", ""]
+	 *           ["Royal-Mail", "royal-mail", ""]
+	 *           ["Acme Freight", "other", "Acme Freight"]
+	 *
+	 * @param string $cell     Provider cell.
+	 * @param string $provider Expected _shipment_provider.
+	 * @param string $name     Expected _provider_name.
+	 */
+	public function test_provider_cell_maps_to_a_known_or_custom_provider( string $cell, string $provider, string $name ): void {
+		$order = OrderHelper::create_order();
+
+		$this->import_csv( "order_number,tracking_number,shipment_provider\n{$order->get_id()},TRK-1,{$cell}\n" );
+
+		$fulfillment = $this->fulfillments_of( $order )[0];
+		$this->assertSame( $provider, $fulfillment->get_shipment_provider() );
+		$this->assertSame( $name, (string) $fulfillment->get_meta( '_provider_name', true ) );
+	}
+
+	/**
+	 * @testdox A listener that changes the fulfillment and throws after the write leaves the row imported and notified, keeps a later row from duplicating it and does not block later order updates.
+	 * @testWith ["woocommerce_fulfillment_after_create", "created"]
+	 *           ["woocommerce_fulfillment_after_update", "updated"]
+	 *
+	 * @param string $hook   Action whose listener throws once.
+	 * @param string $status Expected status of the first row.
+	 */
+	public function test_listener_throwing_after_the_write_keeps_the_row_imported( string $hook, string $status ): void {
+		$order = OrderHelper::create_order();
+		$other = OrderHelper::create_order();
+		$id    = $order->get_id();
+		if ( FulfillmentsCsvImporter::STATUS_UPDATED === $status ) {
+			$this->import_csv( "order_number,tracking_number,shipment_provider\n{$id},TRK-1,fedex\n" );
+		} else {
+			$item = current( $order->get_items() )->get_id();
+			$this->import_csv( "order_number,tracking_number,shipment_provider,tracking_url,items\n{$id},TRK-0,ups,,{$item}:1\n" );
+		}
+		$throws = 1;
+		add_action(
+			$hook,
+			function ( $fulfillment ) use ( &$throws ) {
+				if ( $throws-- > 0 ) {
+					$fulfillment->set_tracking_url( 'https://example.com/listener' );
+					$fulfillment->set_status( 'unfulfilled' );
+					throw new \RuntimeException( 'Listener failed.' );
+				}
+			},
+			5
+		);
+		$notified = array();
+		$collect  = function ( $order_id, $fulfillment ) use ( &$notified, $id ) {
+			if ( $id === $order_id ) {
+				$notified[] = $fulfillment->get_status() . '|' . $fulfillment->get_tracking_url();
+			}
+		};
+		add_action( 'woocommerce_fulfillment_created_notification', $collect, 10, 2 );
+		add_action( 'woocommerce_fulfillment_updated_notification', $collect, 10, 2 );
+
+		$result = $this->import_csv( "order_number,tracking_number,shipment_provider\n{$id},TRK-1,ups\n{$id},TRK-1,dhl\n{$other->get_id()},TRK-2,ups\n{$id},TRK-3,ups\n", array( 'notify_customer' => true ) );
+
+		$this->assertSame( array( $status, FulfillmentsCsvImporter::STATUS_SKIPPED, FulfillmentsCsvImporter::STATUS_CREATED, FulfillmentsCsvImporter::STATUS_FAILED ), array_column( $result['rows'], 'status' ) );
+		$this->assertTrue( $result['rows'][0]['notified'], 'The written row is notified' );
+		$this->assertSame( array( 'fulfilled|' ), $notified, 'The notification gets the stored fulfillment, without the unsaved listener changes' );
+		$this->assertSame( FulfillmentsCsvImporter::CODE_NO_ITEMS, $result['rows'][3]['code'], 'The saved row counts as fulfilled for a later row' );
+		$this->assertCount( FulfillmentsCsvImporter::STATUS_UPDATED === $status ? 1 : 2, $this->fulfillments_of( $order ) );
+		$this->assertFalse( doing_action( $hook ), 'The interrupted action is taken off the filter stack' );
+		$this->assertSame( 'fulfilled', wc_get_order( $other->get_id() )->get_meta( '_fulfillment_status' ), 'A later row still updates its order' );
+	}
+
+	/**
+	 * @testdox A save that fails before the write is failed even when a listener saved another fulfillment first.
+	 * @testWith ["woocommerce_fulfillment_before_create", "created"]
+	 *           ["woocommerce_fulfillment_before_update", "updated"]
+	 *
+	 * @param string $hook   Filter whose callback saves another fulfillment and then throws once.
+	 * @param string $status Expected status of the retried row.
+	 */
+	public function test_nested_save_does_not_mark_a_failed_row_as_written( string $hook, string $status ): void {
+		$order = OrderHelper::create_order();
+		$id    = $order->get_id();
+		if ( FulfillmentsCsvImporter::STATUS_UPDATED === $status ) {
+			$this->import_csv( "order_number,tracking_number,shipment_provider\n{$id},TRK-A,fedex\n" );
+		}
+		$other  = FulfillmentsHelper::create_fulfillment( array( 'entity_id' => (string) OrderHelper::create_order()->get_id() ) );
+		$throws = 1;
+		add_filter(
+			$hook,
+			function ( $fulfillment ) use ( &$throws, $other, $status ) {
+				if ( 'TRK-A' === $fulfillment->get_tracking_number() && $throws-- > 0 ) {
+					// The nested save fires the same after-write action the row's own save would.
+					if ( FulfillmentsCsvImporter::STATUS_CREATED === $status ) {
+						FulfillmentsHelper::create_fulfillment( array( 'entity_id' => $other->get_entity_id() ) );
+					} else {
+						$other->set_status( 'fulfilled' );
+						$other->save();
+					}
+					throw new \RuntimeException( 'Blocked after a nested save.' );
+				}
+				return $fulfillment;
+			}
+		);
+
+		$result = $this->import_csv( "order_number,tracking_number,shipment_provider\n{$id},TRK-A,ups\n{$id},TRK-A,ups\n" );
+
+		$this->assertSame( array( FulfillmentsCsvImporter::STATUS_FAILED, $status ), array_column( $result['rows'], 'status' ) );
+		$this->assertCount( 1, $this->fulfillments_of( $order ) );
+		$this->assertArrayNotHasKey( PHP_INT_MIN, $GLOBALS['wp_filter'][ str_replace( 'before', 'after', $hook ) ]->callbacks, 'The write listener is removed' );
+	}
+
+	/**
+	 * @testdox A blocked update leaves none of its values behind for a later row of the same fulfillment.
+	 */
+	public function test_blocked_update_does_not_leak_its_values_into_a_later_row(): void {
+		$order = OrderHelper::create_order();
+		$id    = $order->get_id();
+		$this->import_csv( "order_number,tracking_number,shipment_provider,tracking_url\n{$id},TRK-1,ups,https://example.com/1\n" );
+		$blocks = 1;
+		add_filter(
+			'woocommerce_fulfillment_before_update',
+			function ( $fulfillment ) use ( &$blocks ) {
+				if ( $blocks-- > 0 ) {
+					throw new FulfillmentException( 'Blocked once.' );
+				}
+				return $fulfillment;
+			}
+		);
+
+		$result = $this->import_csv( "order_number,tracking_number,shipment_provider,tracking_url\n{$id},TRK-1,fedex,https://example.com/bad\n{$id},TRK-1,dhl,\n" );
+
+		$this->assertSame( array( FulfillmentsCsvImporter::STATUS_FAILED, FulfillmentsCsvImporter::STATUS_UPDATED ), array_column( $result['rows'], 'status' ) );
+		$stored = $this->fulfillments_of( $order )[0];
+		$this->assertSame( 'dhl', $stored->get_shipment_provider() );
+		$this->assertSame( 'https://example.com/1', $stored->get_tracking_url() );
+	}
+
+	/**
+	 * @testdox A row that throws after changing a stored fulfillment in memory leaves nothing behind for a later row.
+	 */
+	public function test_row_that_throws_before_the_save_leaves_no_values_behind(): void {
+		$order = OrderHelper::create_order();
+		$id    = $order->get_id();
+		$item  = current( $order->get_items() )->get_id();
+		$this->import_csv( "order_number,tracking_number,shipment_provider,tracking_url,items\n{$id},TRK-1,ups,,{$item}:1\n" );
+		$throws = 1;
+		add_filter(
+			'woocommerce_fulfillment_shipping_providers',
+			function ( $providers ) use ( &$throws ) {
+				if ( $throws-- > 0 ) {
+					throw new \RuntimeException( 'Provider service down.' );
+				}
+				return $providers;
+			},
+			1
+		);
+
+		$result = $this->import_csv( "order_number,tracking_number,shipment_provider,tracking_url,items\n{$id},TRK-1,ups,,{$item}:2\n{$id},TRK-1,UPS,,\n" );
+
+		$this->assertSame( FulfillmentsCsvImporter::CODE_ROW_FAILED, $result['rows'][0]['code'] );
+		$this->assertSame( 1, $this->fulfillments_of( $order )[0]->get_items()[0]['qty'], 'The failed row quantity is not saved by a later row' );
+	}
+
+	/**
+	 * @testdox The provider lookup runs again after it throws once.
+	 */
+	public function test_provider_lookup_is_retried_after_it_throws(): void {
+		$first  = OrderHelper::create_order();
+		$second = OrderHelper::create_order();
+		$throws = 1;
+		add_filter(
+			'woocommerce_fulfillment_shipping_providers',
+			function ( $providers ) use ( &$throws ) {
+				if ( $throws-- > 0 ) {
+					throw new \RuntimeException( 'Provider service down.' );
+				}
+				return $providers;
+			},
+			1
+		);
+
+		$result = $this->import_csv( "order_number,tracking_number,shipment_provider\n{$first->get_id()},TRK-1,UPS\n{$second->get_id()},TRK-2,UPS\n" );
+
+		$this->assertSame( FulfillmentsCsvImporter::CODE_ROW_FAILED, $result['rows'][0]['code'] );
+		$this->assertSame( 'ups', $this->fulfillments_of( $second )[0]->get_shipment_provider() );
+	}
+
+	/**
+	 * @testdox A repeated order and tracking number pair is skipped across chunks, and a row that failed to save does not count as seen.
+	 */
+	public function test_duplicate_pairs_are_skipped_after_the_first_imported_row(): void {
+		$order  = OrderHelper::create_order();
+		$other  = OrderHelper::create_order();
+		$id     = $order->get_id();
+		$blocks = 1;
+		add_filter(
+			'woocommerce_fulfillment_before_create',
+			function ( $fulfillment ) use ( &$blocks ) {
+				if ( $blocks-- > 0 ) {
+					throw new FulfillmentException( 'Blocked once.' );
+				}
+				return $fulfillment;
+			}
+		);
+
+		$result = $this->import_csv(
+			"order_number,tracking_number,shipment_provider,tracking_url\n{$id},TRK-1,ups,\n{$id},trk-1,ups,\n{$id},TRK-1,fedex,\n{$other->get_id()},TRK-1,ups,\n0{$id},TRK-1,ups,\n",
+			array(),
+			1
+		);
+
+		$this->assertSame( array( FulfillmentsCsvImporter::STATUS_FAILED, FulfillmentsCsvImporter::STATUS_CREATED, FulfillmentsCsvImporter::STATUS_SKIPPED, FulfillmentsCsvImporter::STATUS_CREATED, FulfillmentsCsvImporter::STATUS_SKIPPED ), array_column( $result['rows'], 'status' ), 'The pair is keyed by the resolved order, so 0123 repeats 123' );
+		$this->assertSame( 'Duplicate order and tracking number in this file.', $result['rows'][2]['message'] );
+		$fulfillments = $this->fulfillments_of( $order );
+		$this->assertCount( 1, $fulfillments );
+		$this->assertSame( 'ups', $fulfillments[0]->get_shipment_provider(), 'The skipped duplicate must not change the imported row' );
+		$this->assertCount( 1, $this->fulfillments_of( $other ) );
+	}
+
+	/**
+	 * @testdox A row whose tracking number matches a stored fulfillment of the order, in any case, updates it and keeps its URL when the cell is blank.
+	 */
+	public function test_existing_fulfillment_with_the_same_tracking_number_is_updated(): void {
+		$order = OrderHelper::create_order();
+		$id    = $order->get_id();
+		$this->import_csv( "order_number,tracking_number,shipment_provider,tracking_url\n{$id},TRK-1,ups,https://example.com/1\n" );
+		add_filter(
+			'woocommerce_fulfillment_fulfillment_statuses',
+			fn( $statuses ) => $statuses + array(
+				'delivered' => array(
+					'label'        => 'Delivered',
+					'is_fulfilled' => true,
+				),
+			)
+		);
+		$stored = $this->fulfillments_of( $order )[0];
+		$stored->set_status( 'delivered' );
+		$stored->save();
+		$stored_id = $stored->get_id();
+
+		$result = $this->import_csv( "order_number,tracking_number,shipment_provider,tracking_url\n{$id},trk-1,fedex,\n" );
+
+		$this->assertSame( 1, $result['counts'][ FulfillmentsCsvImporter::STATUS_UPDATED ] );
+		$this->assertSame( 'Fulfillment updated.', $result['rows'][0]['message'] );
+		$this->assertSame( $stored_id, $result['rows'][0]['fulfillment_id'] );
+		$fulfillments = $this->fulfillments_of( $order );
+		$this->assertCount( 1, $fulfillments );
+		$this->assertSame( 'trk-1', $fulfillments[0]->get_tracking_number() );
+		$this->assertSame( 'fedex', $fulfillments[0]->get_shipment_provider() );
+		$this->assertSame( 'https://example.com/1', $fulfillments[0]->get_tracking_url() );
+		$this->assertSame( 'delivered', $fulfillments[0]->get_status(), 'A status that is already fulfilled is kept' );
+	}
+
+	/**
+	 * @testdox A row whose mapped values match the stored fulfillment is skipped without a save or a notification.
+	 */
+	public function test_unchanged_update_is_skipped_without_a_save_or_notification(): void {
+		$order   = OrderHelper::create_order();
+		$item    = current( $order->get_items() )->get_id();
+		$csv     = "order_number,tracking_number,shipment_provider,tracking_url,items\n{$order->get_id()},TRK-1,UPS,HTTPS://example.com/t,{$item}:1\n{$order->get_id()},TRK-2,Acme Freight,,{$item}:1\n";
+		$options = array(
+			'notify_customer' => true,
+			'update_existing' => true,
+		);
+		$this->import_csv( $csv, $options );
+		$updates = did_action( 'woocommerce_fulfillment_after_update' );
+		$emails  = did_action( 'woocommerce_fulfillment_updated_notification' );
+
+		$result = $this->import_csv( $csv, $options );
+
+		$this->assertSame( array( FulfillmentsCsvImporter::STATUS_SKIPPED, FulfillmentsCsvImporter::STATUS_SKIPPED ), array_column( $result['rows'], 'status' ) );
+		$this->assertSame( 'Fulfillment unchanged.', $result['rows'][0]['message'] );
+		$this->assertSame( 0, $result['counts']['notified'] );
+		$this->assertSame( $updates, did_action( 'woocommerce_fulfillment_after_update' ), 'An unchanged row is not saved' );
+		$this->assertSame( $emails, did_action( 'woocommerce_fulfillment_updated_notification' ) );
+	}
+
+	/**
+	 * @testdox A deleted fulfillment with the row's tracking number is not updated; the row creates a new one.
+	 */
+	public function test_deleted_fulfillment_is_not_matched(): void {
+		$order = OrderHelper::create_order();
+		$csv   = "order_number,tracking_number,shipment_provider\n{$order->get_id()},TRK-1,ups\n";
+		$this->import_csv( $csv );
+		$deleted = $this->fulfillments_of( $order )[0];
+		$deleted->delete();
+
+		$result = $this->import_csv( $csv );
+
+		$this->assertSame( FulfillmentsCsvImporter::STATUS_CREATED, $result['rows'][0]['status'] );
+		$this->assertNotSame( $deleted->get_id(), $result['rows'][0]['fulfillment_id'] );
+	}
+
+	/**
+	 * @testdox A matching fulfillment is left alone when updates are off or when it is locked.
+	 * @testWith [false, false, "skipped", null]
+	 *           [true, true, "failed", "fulfillment_locked"]
+	 *
+	 * @param bool        $update_existing Importer update_existing option.
+	 * @param bool        $locked          Whether the stored fulfillment is locked.
+	 * @param string      $status          Expected row status.
+	 * @param string|null $code            Expected row code.
+	 */
+	public function test_matching_fulfillment_is_kept_when_updates_are_off_or_it_is_locked( bool $update_existing, bool $locked, string $status, ?string $code ): void {
+		$order = OrderHelper::create_order();
+		$id    = $order->get_id();
+		$this->import_csv( "order_number,tracking_number,shipment_provider\n{$id},TRK-1,ups\n" );
+		$stored = $this->fulfillments_of( $order )[0];
+		$stored->set_locked( $locked );
+		$stored->save();
+
+		$result = $this->import_csv( "order_number,tracking_number,shipment_provider\n{$id},TRK-1,fedex\n", array( 'update_existing' => $update_existing ) );
+
+		$this->assertSame( $status, $result['rows'][0]['status'] );
+		$this->assertSame( $code, $result['rows'][0]['code'] ?? null );
+		$this->assertSame( 'ups', $this->fulfillments_of( $order )[0]->get_shipment_provider() );
+	}
+
+	/**
+	 * @testdox The resolve-order filter maps custom order numbers, runs for primed orders, and a non-order result fails the row.
+	 */
+	public function test_resolve_order_filter_decides_the_order(): void {
+		$order = OrderHelper::create_order();
+		$other = OrderHelper::create_order();
+		$calls = array();
+		add_filter(
+			'woocommerce_fulfillments_csv_importer_resolve_order',
+			function ( $resolved, $order_number ) use ( $order, $other, &$calls ) {
+				$calls[] = $order_number;
+				if ( 'INV-7' === $order_number ) {
+					return $order;
+				}
+				return (string) $other->get_id() === $order_number ? 'not an order' : $resolved;
+			},
+			10,
+			2
+		);
+
+		$item   = current( $order->get_items() )->get_id();
+		$result = $this->import_csv( "order_number,tracking_number,shipment_provider,tracking_url,items\nINV-7,TRK-1,ups,,{$item}:1\n{$other->get_id()},TRK-2,ups\n{$order->get_id()},TRK-3,ups,,{$item}:1\nINV-7,TRK-4,ups,,{$item}:1\n" );
+
+		$this->assertSame( array( FulfillmentsCsvImporter::STATUS_CREATED, FulfillmentsCsvImporter::STATUS_FAILED, FulfillmentsCsvImporter::STATUS_CREATED, FulfillmentsCsvImporter::STATUS_CREATED ), array_column( $result['rows'], 'status' ) );
+		$this->assertSame( $order->get_id(), $result['rows'][0]['order_id'] );
+		$this->assertSame( FulfillmentsCsvImporter::CODE_ORDER_NOT_FOUND, $result['rows'][1]['code'] );
+		$this->assertSame( array( 'INV-7', (string) $other->get_id(), (string) $order->get_id() ), $calls, 'The filter runs once per order number in a chunk' );
+		$this->assertCount( 0, $this->fulfillments_of( $other ) );
+	}
+
+	/**
+	 * @testdox A row that throws outside the save fails on its own and the rest of the chunk still imports.
+	 */
+	public function test_row_that_throws_fails_alone(): void {
+		$first  = OrderHelper::create_order();
+		$second = OrderHelper::create_order();
+		add_filter(
+			'woocommerce_fulfillments_csv_importer_resolve_order',
+			function ( $order, $order_number ) {
+				if ( 'BOOM' === $order_number ) {
+					throw new \RuntimeException( 'Lookup service down.' );
+				}
+				return $order;
+			},
+			10,
+			2
+		);
+
+		$result = $this->import_csv( "order_number,tracking_number,shipment_provider\n{$first->get_id()},TRK-1,ups\nBOOM,TRK-2,ups\n{$second->get_id()},TRK-3,ups\n" );
+
+		$this->assertSame( array( FulfillmentsCsvImporter::STATUS_CREATED, FulfillmentsCsvImporter::STATUS_FAILED, FulfillmentsCsvImporter::STATUS_CREATED ), array_column( $result['rows'], 'status' ) );
+		$this->assertSame( FulfillmentsCsvImporter::CODE_ROW_FAILED, $result['rows'][1]['code'] );
+		$this->assertSame( 'BOOM', $result['rows'][1]['order_number'] );
+		$this->assertFalse( doing_filter( 'woocommerce_fulfillments_csv_importer_resolve_order' ) );
+	}
+
+	/**
+	 * @testdox Each chunk loads the orders it names by ID in one query, uses them, and checks the filtered query result.
+	 */
+	public function test_chunk_orders_are_loaded_in_one_query(): void {
+		$first   = OrderHelper::create_order();
+		$second  = OrderHelper::create_order();
+		$item    = current( $second->get_items() )->get_id();
+		$queries = array();
+		$primed  = array();
+		add_filter(
+			'woocommerce_order_query_args',
+			function ( $args ) use ( &$queries ) {
+				if ( isset( $args['post__in'] ) ) {
+					$queries[] = array( $args['post__in'], $args['limit'] );
+				}
+				return $args;
+			}
+		);
+		add_filter(
+			'woocommerce_order_query',
+			function ( $orders, $args ) use ( &$queries ) {
+				if ( ! isset( $args['post__in'] ) ) {
+					return $orders;
+				}
+				// The first priming query gets a junk entry, the second returns a non-array.
+				if ( 1 === count( $queries ) ) {
+					foreach ( $orders as $order ) {
+						$order->add_meta_data( '_test_primed', 'yes' );
+					}
+					$orders[] = 'junk';
+					return $orders;
+				}
+				return 'not an array';
+			},
+			10,
+			2
+		);
+		add_filter(
+			'woocommerce_fulfillments_csv_importer_resolve_order',
+			function ( $order ) use ( &$primed ) {
+				$primed[] = $order ? $order->get_meta( '_test_primed' ) : null;
+				return $order;
+			}
+		);
+
+		$result = $this->import_csv(
+			"order_number,tracking_number,shipment_provider\nINV-1,TRK-1,ups\nINV-2,TRK-2,ups\n{$second->get_id()},TRK-3,ups,,{$item}:1\n{$second->get_id()},TRK-4,ups,,{$item}:1\n{$first->get_id()},TRK-5,ups\n",
+			array(),
+			2
+		);
+
+		$this->assertSame(
+			array(
+				array( array( $second->get_id() ), 1 ),
+				array( array( $first->get_id() ), 1 ),
+			),
+			$queries,
+			'A chunk without numeric order numbers runs no query, and IDs are not repeated'
+		);
+		$this->assertSame( array( null, null, 'yes', null ), $primed, 'The primed order is used, and a non-array query result finds nothing' );
+		$this->assertSame( array( FulfillmentsCsvImporter::STATUS_FAILED, FulfillmentsCsvImporter::STATUS_FAILED, FulfillmentsCsvImporter::STATUS_CREATED, FulfillmentsCsvImporter::STATUS_CREATED, FulfillmentsCsvImporter::STATUS_FAILED ), array_column( $result['rows'], 'status' ) );
+	}
+
+	/**
+	 * @testdox A row whose order fulfillments cannot be read fails without caching the failure.
+	 */
+	public function test_unreadable_fulfillments_fail_the_row(): void {
+		global $wpdb;
+		$order = OrderHelper::create_order();
+		$reads = 0;
+		add_filter(
+			'query',
+			function ( $query ) use ( &$reads ) {
+				if ( false !== strpos( $query, 'wc_order_fulfillments WHERE entity_type' ) ) {
+					++$reads;
+					return str_replace( 'wc_order_fulfillments', 'wc_order_fulfillments_missing', $query );
+				}
+				return $query;
+			}
+		);
+		$suppress = $wpdb->suppress_errors( true );
+
+		$result = $this->import_csv( "order_number,tracking_number,shipment_provider\n{$order->get_id()},TRK-1,ups\n{$order->get_id()},TRK-2,ups\n" );
+
+		$wpdb->suppress_errors( $suppress );
+		$this->assertSame( array( FulfillmentsCsvImporter::CODE_STORE_READ_FAILED, FulfillmentsCsvImporter::CODE_STORE_READ_FAILED ), array_column( $result['rows'], 'code' ) );
+		$this->assertSame( 2, $reads, 'A failed read is not cached, so the next row reads again' );
+	}
+
+	/**
+	 * @testdox A run resumed through the session at any chunk size imports the same rows as one chunk and refuses a replay.
+	 * @testWith [1]
+	 *           [2]
+	 *           [3]
+	 *           [4]
+	 *           [5]
+	 *           [6]
+	 *
+	 * @param int $limit Data rows per chunk.
+	 */
+	public function test_run_resumed_through_the_session_matches_one_chunk( int $limit ): void {
+		$ids     = array_map( fn() => (string) OrderHelper::create_order()->get_id(), range( 1, 4 ) );
+		$file    = $this->make_csv( "order_number,tracking_number,shipment_provider\n\n{$ids[0]},TRK-1,ups\n{$ids[1]},TRK-2,\"ups, ground\"\n\n,,\n{$ids[2]},TRK-3,ups\n{$ids[2]},trk-3,ups\nINV-9,TRK-4,ups\n{$ids[3]},TRK-5,ups\n" );
+		$parsed  = ( new FulfillmentsCsvImporter( $file ) )->parse_headers();
+		$session = ImportSession::create( 1, $file, ',', $parsed['headers'], $parsed['total'], false, true );
+		$session->freeze_run_settings( self::IMPORT_MAPPING, false, true );
+		$rows     = array();
+		$consumed = 0;
+		$guard    = 0;
+		do {
+			$session = ImportSession::load( 1, $session->token() );
+			$offset  = $session->processed();
+			$chunk   = ( new FulfillmentsCsvImporter( $file, array( 'update_existing' => $session->update_existing() ) ) )->import_chunk(
+				$limit,
+				$session->frozen_mapping(),
+				array(
+					'byte_offset'         => $session->byte_offset(),
+					'next_record_number'  => $session->next_record_number(),
+					'seen_tracking_pairs' => $session->seen_tracking_pairs(),
+				)
+			);
+			$this->assertTrue( $session->record_chunk( $offset, $chunk ) );
+			$this->assertFalse( ImportSession::load( 1, $session->token() )->record_chunk( $offset, $chunk ), 'A replay of the chunk is refused' );
+			$rows      = array_merge( $rows, $chunk['rows'] );
+			$consumed += $chunk['consumed'];
+		} while ( ! $chunk['eof'] && ++$guard < 20 );
+		$session = ImportSession::load( 1, $session->token() );
+		foreach ( $ids as $id ) {
+			WC_Data_Store::load( 'order-fulfillment' )->delete_by_entity( WC_Order::class, $id );
+		}
+		$single = ( new FulfillmentsCsvImporter( $file ) )->import_chunk( 200, self::IMPORT_MAPPING );
+
+		$strip = fn( $row ) => array_diff_key( $row, array( 'fulfillment_id' => 0 ) );
+		$this->assertSame( array_map( $strip, $single['rows'] ), array_map( $strip, $rows ) );
+		$this->assertSame( array( 3, 4, 7, 8, 9, 10 ), array_column( $rows, 'row' ), 'Physical row numbers survive blank lines and chunk edges' );
+		$this->assertSame( FulfillmentsCsvImporter::STATUS_SKIPPED, $rows[3]['status'], 'The dedupe set is carried by the session' );
+		$this->assertSame( $parsed['total'], $consumed );
+		$this->assertSame( $parsed['total'], $session->processed() );
+		$this->assertSame( $single['counts'], $session->counts() );
+	}
+
+	/**
+	 * @testdox The chunk limit falls back to and is capped by the resolved chunk size.
+	 * @testWith [100, 2]
+	 *           [0, 2]
+	 *           [1, 1]
+	 *
+	 * @param int $limit    Requested limit.
+	 * @param int $consumed Expected rows consumed.
+	 */
+	public function test_chunk_limit_is_capped_by_the_resolved_chunk_size( int $limit, int $consumed ): void {
+		add_filter( 'woocommerce_fulfillments_csv_importer_chunk_size', fn() => 2 );
+		$id  = OrderHelper::create_order()->get_id();
+		$sut = new FulfillmentsCsvImporter( $this->make_csv( "order_number,tracking_number,shipment_provider\n{$id},T-1,ups\n{$id},T-2,ups\n{$id},T-3,ups\n" ) );
+
+		$chunk = $sut->import_chunk( $limit, self::IMPORT_MAPPING );
+
+		$this->assertSame( $consumed, $chunk['consumed'] );
+		$this->assertCount( $consumed, $chunk['rows'] );
+		$this->assertFalse( $chunk['eof'] );
+	}
+
+	/**
+	 * @testdox A chunk-level problem returns an error and writes nothing.
+	 */
+	public function test_chunk_errors_write_nothing(): void {
+		$order = OrderHelper::create_order();
+		$sut   = new FulfillmentsCsvImporter( $this->make_csv( "order_number,tracking_number,shipment_provider\n{$order->get_id()},T-1,ups\n" ) );
+
+		$missing_column = $sut->import_chunk( 10, array_slice( self::IMPORT_MAPPING, 0, 2, true ) );
+		$missing_file   = ( new FulfillmentsCsvImporter( '/path/that/does/not/exist.csv' ) )->import_chunk( 10, self::IMPORT_MAPPING );
+
+		$this->assertSame( array( 'error' ), array_keys( $missing_column ) );
+		$this->assertSame( 'missing_required_columns', $missing_column['error']['code'] );
+		$this->assertStringContainsString( 'shipment_provider', $missing_column['error']['message'] );
+		$this->assertSame( 'file_not_readable', $missing_file['error']['code'] );
+		$this->assertCount( 0, $this->fulfillments_of( $order ) );
+	}
+
+	/**
+	 * Create an order with item "a" (quantity 4, SKU "DUMMY SKU"), item "b" (quantity 2, SKU "SKU-B")
+	 * and a third item whose product was deleted.
+	 *
+	 * @return array{0: WC_Order, 1: int, 2: int} The order and the IDs of items a and b.
+	 */
+	private function make_two_item_order(): array {
+		$order     = OrderHelper::create_order();
+		$product_b = \WC_Helper_Product::create_simple_product();
+		$product_b->set_sku( 'SKU-B' );
+		$product_b->save();
+		$item_b  = $order->add_product( $product_b, 2 );
+		$deleted = \WC_Helper_Product::create_simple_product();
+		$order->add_product( $deleted, 1 );
+		$order->save();
+		$deleted->delete( true );
+		return array( $order, (int) current( $order->get_items() )->get_id(), (int) $item_b );
+	}
+
+	/**
+	 * @testdox The items cell takes item IDs and SKUs, skips empty entries and adds up a repeated item up to the ordered quantity.
+	 */
+	public function test_items_cell_selects_items_by_id_and_sku(): void {
+		list( $order, $item_a, $item_b ) = $this->make_two_item_order();
+
+		$result = $this->import_csv( "order_number,tracking_number,shipment_provider,tracking_url,items\n{$order->get_id()},TRK-1,ups,,\"{$item_a}:1| |SKU:Sku-B:1; {$item_a} : 3\"\n" );
+
+		$this->assertSame( FulfillmentsCsvImporter::STATUS_CREATED, $result['rows'][0]['status'] );
+		$this->assert_items(
+			array(
+				$item_a => 4,
+				$item_b => 1,
+			),
+			$this->fulfillments_of( $order )[0]->get_items()
+		);
+	}
+
+	/**
+	 * @testdox An invalid items cell fails the row with invalid_items and a message saying why.
+	 * @testWith ["{a}:5", "Item quantity 5 exceeds the quantity left to fulfill 4."]
+	 *           ["{a}:3|{a}:2", "Item quantity 5 exceeds the quantity left to fulfill 4."]
+	 *           ["{b}:3", "Item quantity 3 exceeds the quantity left to fulfill 2."]
+	 *           ["99999999:1", "Item ID 99999999 is not part of this order."]
+	 *           ["{a}:1.5", "Item quantity must be a positive integer."]
+	 *           ["{a}:0", "Item quantity must be a positive integer."]
+	 *           ["{a}", "Invalid items entry: {a}."]
+	 *           ["{a}abc:1", "Item ID {a}abc is not part of this order."]
+	 *           ["sku:NOPE:1", "SKU NOPE was not found on the order."]
+	 *           ["sku:SKU-B", "Invalid items entry: sku:SKU-B."]
+	 *           ["{a}:1:2", "Invalid items entry: {a}:1:2."]
+	 *           ["0", "Invalid items entry: 0."]
+	 *           ["sku::1", "SKU  was not found on the order."]
+	 *           ["|;", "The items cell has no item entries."]
+	 *
+	 * @param string $cell    Items cell; {a} and {b} stand for the item IDs.
+	 * @param string $message Expected message.
+	 */
+	public function test_invalid_items_cell_fails_the_row( string $cell, string $message ): void {
+		list( $order, $item_a, $item_b ) = $this->make_two_item_order();
+		$replace                         = array(
+			'{a}' => $item_a,
+			'{b}' => $item_b,
+		);
+
+		$result = $this->import_csv( "order_number,tracking_number,shipment_provider,tracking_url,items\n{$order->get_id()},TRK-1,ups,,\"" . strtr( $cell, $replace ) . "\"\n" );
+
+		$this->assertSame( FulfillmentsCsvImporter::CODE_INVALID_ITEMS, $result['rows'][0]['code'] ?? null );
+		$this->assertSame( strtr( $message, $replace ), $result['rows'][0]['message'] );
+		$this->assertCount( 0, $this->fulfillments_of( $order ) );
+	}
+
+	/**
+	 * @testdox Items default to and are capped by what is left to fulfill after refunds and the order's other fulfillments.
+	 * @testWith ["{a}:1", "TRK-NEW", "", "{a}:3|{b}:1|{c}:1"]
+	 *           ["{a}:1", "TRK-NEW", "{a}:3", "{a}:3"]
+	 *           ["{a}:1", "TRK-NEW", "{a}:4", "Item quantity 4 exceeds the quantity left to fulfill 3."]
+	 *           ["{a}:1", "TRK-NEW", "{b}:2", "Item quantity 2 exceeds the quantity left to fulfill 1."]
+	 *           ["{a}:1", "TRK-OLD", "{a}:4", "{a}:4"]
+	 *           ["{a}:4|{b}:1|{c}:1", "TRK-NEW", "", "This order has no items left to fulfill."]
+	 *           ["{a}:4", "TRK-NEW", "{a}:1", "Item quantity 1 exceeds the quantity left to fulfill 0."]
+	 *
+	 * @param string $stored   Items of the stored fulfillment TRK-OLD.
+	 * @param string $tracking Tracking number of the row.
+	 * @param string $cell     Items cell of the row.
+	 * @param string $expected Items of the imported fulfillment, or the failure message.
+	 */
+	public function test_items_are_limited_to_what_is_left_to_fulfill( string $stored, string $tracking, string $cell, string $expected ): void {
+		list( $order, $item_a, $item_b ) = $this->make_two_item_order();
+		$replace                         = array(
+			'{a}' => $item_a,
+			'{b}' => $item_b,
+			'{c}' => array_keys( $order->get_items() )[2],
+		);
+		$to_items                        = static function ( string $entries ) use ( $replace ): array {
+			return array_map(
+				static function ( $entry ) {
+					list( $item_id, $qty ) = array_map( 'intval', explode( ':', $entry ) );
+					return array(
+						'item_id' => $item_id,
+						'qty'     => $qty,
+					);
+				},
+				explode( '|', strtr( $entries, $replace ) )
+			);
+		};
+		FulfillmentsHelper::create_fulfillment(
+			array(
+				'entity_id' => (string) $order->get_id(),
+				'status'    => 'fulfilled',
+			),
+			array(
+				'_tracking_number' => 'TRK-OLD',
+				'_items'           => $to_items( $stored ),
+			)
+		);
+		wc_create_refund(
+			array(
+				'order_id'   => $order->get_id(),
+				'amount'     => 1,
+				'line_items' => array(
+					$item_b => array(
+						'qty'          => 1,
+						'refund_total' => 1,
+					),
+				),
+			)
+		);
+
+		$result = $this->import_csv( "order_number,tracking_number,shipment_provider,tracking_url,items\n{$order->get_id()},{$tracking},ups,,\"" . strtr( $cell, $replace ) . "\"\n", array( 'update_existing' => true ) );
+
+		$items = array();
+		foreach ( $this->fulfillments_of( $order ) as $fulfillment ) {
+			$items = $tracking === $fulfillment->get_tracking_number() ? $fulfillment->get_items() : $items;
+		}
+		if ( '{' === $expected[0] ) {
+			$this->assertNotSame( FulfillmentsCsvImporter::STATUS_FAILED, $result['rows'][0]['status'] );
+			$this->assert_items( array_column( $to_items( $expected ), 'qty', 'item_id' ), $items );
+		} else {
+			$this->assertSame( $expected, $result['rows'][0]['message'] );
+			$this->assertCount( 1, $this->fulfillments_of( $order ) );
+		}
+	}
+
+	/**
+	 * @testdox A SKU shared by two line items of the order fails the row instead of picking one.
+	 */
+	public function test_sku_shared_by_two_line_items_fails_the_row(): void {
+		list( $order, , $item_b ) = $this->make_two_item_order();
+		$order->add_product( $order->get_item( $item_b )->get_product(), 1 );
+		$order->save();
+
+		$result = $this->import_csv( "order_number,tracking_number,shipment_provider,tracking_url,items\n{$order->get_id()},TRK-1,ups,,sku:sku-b:1\n" );
+
+		$this->assertSame( FulfillmentsCsvImporter::CODE_INVALID_ITEMS, $result['rows'][0]['code'] ?? null );
+		$this->assertSame( 'SKU sku-b matches more than one item of this order. Use the item ID instead.', $result['rows'][0]['message'] );
+	}
+
+	/**
+	 * @testdox A SKU entry matches the product SKU ignoring case for non-ASCII letters too.
+	 */
+	public function test_sku_entry_matches_a_non_ascii_sku_ignoring_case(): void {
+		list( $order, , $item_b ) = $this->make_two_item_order();
+		$product                  = $order->get_item( $item_b )->get_product();
+		$product->set_sku( "CAF\u{00C9}-1" );
+		$product->save();
+
+		$result = $this->import_csv( "order_number,tracking_number,shipment_provider,tracking_url,items\n{$order->get_id()},TRK-1,ups,,sku:caf\u{00E9}-1:1\n" );
+
+		$this->assertSame( FulfillmentsCsvImporter::STATUS_CREATED, $result['rows'][0]['status'], $result['rows'][0]['message'] );
+		$this->assert_items( array( $item_b => 1 ), $this->fulfillments_of( $order )[0]->get_items() );
+	}
+
+	/**
+	 * @testdox On an update a blank items cell keeps the stored items and a filled one replaces them.
+	 */
+	public function test_items_on_update_are_kept_when_blank_and_replaced_when_given(): void {
+		list( $order, $item_a, $item_b ) = $this->make_two_item_order();
+		$id                              = $order->get_id();
+		$this->import_csv( "order_number,tracking_number,shipment_provider,tracking_url,items\n{$id},TRK-1,ups,,{$item_b}:1\n" );
+
+		$this->import_csv( "order_number,tracking_number,shipment_provider,tracking_url,items\n{$id},TRK-1,fedex,,\n" );
+		$kept = $this->fulfillments_of( $order )[0]->get_items();
+		$this->import_csv( "order_number,tracking_number,shipment_provider,tracking_url,items\n{$id},TRK-1,fedex,,{$item_a}:2\n" );
+
+		$this->assert_items( array( $item_b => 1 ), $kept, 'A blank items cell must not widen a partial fulfillment to every item' );
+		$this->assert_items( array( $item_a => 2 ), $this->fulfillments_of( $order )[0]->get_items() );
+	}
+
+	/**
+	 * @testdox With notify_customer on, a newly fulfilled row fires the created notification and an update of a fulfilled one the updated notification.
+	 * @testWith [true]
+	 *           [false]
+	 *
+	 * @param bool $notify Importer notify_customer option.
+	 */
+	public function test_notify_customer_fires_the_fulfillment_notifications( bool $notify ): void {
+		$order = OrderHelper::create_order();
+		$id    = $order->get_id();
+		$item  = current( $order->get_items() )->get_id();
+		FulfillmentsHelper::create_fulfillment(
+			array(
+				'entity_id' => (string) $id,
+				'status'    => 'unfulfilled',
+			),
+			array(
+				'_tracking_number' => 'TRK-2',
+				'_items'           => array(
+					array(
+						'item_id' => $item,
+						'qty'     => 1,
+					),
+				),
+			)
+		);
+		$fired = array();
+		add_action(
+			'woocommerce_fulfillment_created_notification',
+			function ( $order_id, $fulfillment, $notified_order ) use ( &$fired ) {
+				$fired[] = array( 'created', $order_id, $fulfillment->get_tracking_number(), $notified_order->get_id() );
+			},
+			10,
+			3
+		);
+		add_action(
+			'woocommerce_fulfillment_updated_notification',
+			function ( $order_id, $fulfillment, $notified_order, $note ) use ( &$fired ) {
+				$fired[] = array( 'updated', $order_id, $fulfillment->get_tracking_number(), $notified_order->get_id(), $note );
+			},
+			10,
+			4
+		);
+
+		$first  = $this->import_csv( "order_number,tracking_number,shipment_provider\n{$id},TRK-1,ups\n{$id},TRK-2,ups\n", array( 'notify_customer' => $notify ) );
+		$second = $this->import_csv( "order_number,tracking_number,shipment_provider\n{$id},TRK-1,fedex\n", array( 'notify_customer' => $notify ) );
+
+		$expected = array(
+			array( 'created', $id, 'TRK-1', $id ),
+			array( 'created', $id, 'TRK-2', $id ),
+			array( 'updated', $id, 'TRK-1', $id, '' ),
+		);
+		$this->assertSame( $notify ? $expected : array(), $fired );
+		$this->assertSame( $notify ? 2 : 0, $first['counts']['notified'] );
+		$this->assertSame( $notify ? 1 : 0, $second['counts']['notified'] );
+		$this->assertSame( array( FulfillmentsCsvImporter::STATUS_CREATED, FulfillmentsCsvImporter::STATUS_UPDATED, FulfillmentsCsvImporter::STATUS_UPDATED ), array_column( array_merge( $first['rows'], $second['rows'] ), 'status' ) );
+		$this->assertSame( array( $notify, $notify, $notify ), array_column( array_merge( $first['rows'], $second['rows'] ), 'notified' ) );
+		foreach ( $this->fulfillments_of( $order ) as $fulfillment ) {
+			$this->assertTrue( $fulfillment->get_is_fulfilled(), 'An update fulfills a fulfillment that was not fulfilled' );
+		}
+	}
+
+	/**
+	 * @testdox No notification fires for a row that a listener saved as not fulfilled.
+	 */
+	public function test_no_notification_for_a_fulfillment_saved_as_not_fulfilled(): void {
+		$order = OrderHelper::create_order();
+		add_filter(
+			'woocommerce_fulfillment_before_create',
+			function ( $fulfillment ) {
+				$fulfillment->set_status( 'unfulfilled' );
+				return $fulfillment;
+			}
+		);
+		$fired = did_action( 'woocommerce_fulfillment_created_notification' );
+
+		$result = $this->import_csv( "order_number,tracking_number,shipment_provider\n{$order->get_id()},TRK-1,ups\n", array( 'notify_customer' => true ) );
+
+		$this->assertSame( FulfillmentsCsvImporter::STATUS_CREATED, $result['rows'][0]['status'] );
+		$this->assertFalse( $result['rows'][0]['notified'] );
+		$this->assertSame( $fired, did_action( 'woocommerce_fulfillment_created_notification' ) );
+	}
+
+	/**
+	 * @testdox A notification listener that changes the fulfillment and throws leaves nothing behind for a later row.
+	 */
+	public function test_failing_notification_does_not_leak_its_changes_into_a_later_row(): void {
+		$order  = OrderHelper::create_order();
+		$id     = $order->get_id();
+		$item   = current( $order->get_items() )->get_id();
+		$throws = 1;
+		add_action(
+			'woocommerce_fulfillment_created_notification',
+			function ( $order_id, $fulfillment ) use ( &$throws ) {
+				if ( $throws-- > 0 ) {
+					$fulfillment->set_tracking_number( 'TRK-2' );
+					throw new \Exception( 'Mail server down' );
+				}
+			},
+			10,
+			2
+		);
+
+		$result = $this->import_csv( "order_number,tracking_number,shipment_provider,tracking_url,items\n{$id},TRK-1,ups,,{$item}:1\n{$id},TRK-2,ups,,{$item}:1\n", array( 'notify_customer' => true ) );
+
+		$this->assertSame( array( FulfillmentsCsvImporter::STATUS_CREATED, FulfillmentsCsvImporter::STATUS_CREATED ), array_column( $result['rows'], 'status' ) );
+		$this->assertCount( 2, $this->fulfillments_of( $order ) );
+	}
+
+	/**
+	 * @testdox A notification listener that throws leaves the row imported and not counted as notified.
+	 */
+	public function test_failing_notification_keeps_the_row_imported(): void {
+		$order  = OrderHelper::create_order();
+		$other  = OrderHelper::create_order();
+		$throws = 1;
+		add_action(
+			'woocommerce_fulfillment_created_notification',
+			function () use ( &$throws ) {
+				if ( $throws-- > 0 ) {
+					throw new \Exception( 'Mail server down' );
+				}
+			}
+		);
+
+		$result = $this->import_csv( "order_number,tracking_number,shipment_provider\n{$order->get_id()},TRK-1,ups\n{$other->get_id()},TRK-2,ups\n", array( 'notify_customer' => true ) );
+
+		$this->assertSame( 2, $result['counts'][ FulfillmentsCsvImporter::STATUS_CREATED ] );
+		$this->assertSame( array( false, true ), array_column( $result['rows'], 'notified' ), 'A later row is notified normally' );
+		$this->assertFalse( doing_action( 'woocommerce_fulfillment_created_notification' ), 'The interrupted action is taken off the filter stack' );
+		$this->assertCount( 1, $this->fulfillments_of( $order ) );
+	}
 }
diff --git a/plugins/woocommerce/tests/php/src/Admin/Features/Fulfillments/Importer/ImportSessionTest.php b/plugins/woocommerce/tests/php/src/Admin/Features/Fulfillments/Importer/ImportSessionTest.php
index fd301d8f296..9aaab0d843a 100644
--- a/plugins/woocommerce/tests/php/src/Admin/Features/Fulfillments/Importer/ImportSessionTest.php
+++ b/plugins/woocommerce/tests/php/src/Admin/Features/Fulfillments/Importer/ImportSessionTest.php
@@ -2,6 +2,7 @@

 namespace Automattic\WooCommerce\Tests\Admin\Features\Fulfillments\Importer;

+use Automattic\WooCommerce\Admin\Features\Fulfillments\Importer\FulfillmentsCsvImporter;
 use Automattic\WooCommerce\Admin\Features\Fulfillments\Importer\ImportSession;
 use Automattic\WooCommerce\Internal\Admin\ImportExport\CSVUploadHelper;
 use Automattic\WooCommerce\Tests\Internal\TransientFiles\TransientFilesTestStreamWrapper;
@@ -581,4 +582,169 @@ class ImportSessionTest extends \WC_Unit_Test_Case {
 			}
 		);
 	}
+
+	/**
+	 * Build a result in the shape FulfillmentsCsvImporter::import_chunk() returns.
+	 *
+	 * @param int  $consumed    Data rows the chunk processed.
+	 * @param int  $created     Rows created by the chunk.
+	 * @param int  $byte_offset Position the next chunk resumes from.
+	 * @param bool $eof         Whether the chunk reached the end of the file.
+	 * @return array<string, mixed>
+	 */
+	private function chunk_result( int $consumed, int $created, int $byte_offset, bool $eof = false ): array {
+		return array(
+			'counts'              => array(
+				FulfillmentsCsvImporter::STATUS_CREATED => $created,
+				FulfillmentsCsvImporter::STATUS_UPDATED => 1,
+				FulfillmentsCsvImporter::STATUS_SKIPPED => 0,
+				FulfillmentsCsvImporter::STATUS_FAILED  => 0,
+				'notified'                              => 0,
+			),
+			'rows'                => array(
+				array(
+					'row'     => $byte_offset,
+					'status'  => FulfillmentsCsvImporter::STATUS_CREATED,
+					'message' => 'Fulfillment created.',
+				),
+			),
+			'seen_tracking_pairs' => array( 'pair-' . $byte_offset => true ),
+			'consumed'            => $consumed,
+			'byte_offset'         => $byte_offset,
+			'next_record_number'  => $consumed + 2,
+			'eof'                 => $eof,
+		);
+	}
+
+	/**
+	 * @testdox record_chunk() advances processed, adds counts and stores the resume position and the last chunk's rows.
+	 */
+	public function test_record_chunk_persists_progress(): void {
+		$session = $this->make_session( 81 );
+
+		$this->assertTrue( $session->record_chunk( 0, $this->chunk_result( 10, 7, 400 ) ) );
+		$this->assertTrue( $session->record_chunk( 10, $this->chunk_result( 5, 3, 650, true ) ) );
+
+		$reloaded = ImportSession::load( 81, $session->token() );
+		$this->assertNotNull( $reloaded );
+		$this->assertSame( 15, $reloaded->processed(), 'processed is the chunk offset plus the rows it consumed' );
+		$this->assertSame( 650, $reloaded->byte_offset() );
+		$this->assertSame( 7, $reloaded->next_record_number() );
+		$this->assertSame( 10, $reloaded->counts()[ FulfillmentsCsvImporter::STATUS_CREATED ], 'Counts of each chunk are added up' );
+		$this->assertSame( 2, $reloaded->counts()[ FulfillmentsCsvImporter::STATUS_UPDATED ] );
+		$this->assertSame( array( 'pair-650' => true ), $reloaded->seen_tracking_pairs(), 'The dedupe set is replaced, not merged' );
+		$last = $reloaded->last_chunk();
+		$this->assertSame( 10, $last['offset'] );
+		$this->assertSame( $this->chunk_result( 5, 3, 650 )['rows'], $last['rows'], 'Only the last chunk keeps its rows, so a replay of it can return them' );
+		$this->assertTrue( $last['eof'] );
+	}
+
+	/**
+	 * @testdox record_chunk() refuses an offset other than the recorded progress, so a replayed chunk is never counted twice.
+	 */
+	public function test_record_chunk_refuses_an_offset_that_is_not_the_recorded_progress(): void {
+		$session = $this->make_session( 82 );
+		$this->assertNull( $session->last_chunk() );
+		$session->record_chunk( 0, $this->chunk_result( 10, 7, 400 ) );
+
+		$this->assertFalse( $session->record_chunk( 0, $this->chunk_result( 10, 7, 400 ) ), 'A replayed offset must be refused' );
+		$this->assertFalse( $session->record_chunk( 20, $this->chunk_result( 10, 7, 800 ) ), 'An offset ahead of the progress must be refused' );
+
+		$reloaded = ImportSession::load( 82, $session->token() );
+		$this->assertSame( 10, $reloaded->processed() );
+		$this->assertSame( 7, $reloaded->counts()[ FulfillmentsCsvImporter::STATUS_CREATED ] );
+		$this->assertSame( 400, $reloaded->byte_offset() );
+	}
+
+	/**
+	 * @testdox record_chunk() refuses an error result, a stale copy of the session, a deleted session and a lost write.
+	 */
+	public function test_record_chunk_refuses_what_it_cannot_store_safely(): void {
+		$session = $this->make_session( 84 );
+		$stale   = ImportSession::load( 84, $session->token() );
+
+		$this->assertFalse( $session->record_chunk( 0, array( 'error' => array( 'code' => 'file_not_readable' ) ) ), 'An error result is refused' );
+		$this->assertTrue( $session->record_chunk( 0, $this->chunk_result( 10, 7, 400 ) ) );
+		$this->assertFalse( $stale->record_chunk( 0, $this->chunk_result( 10, 3, 999 ) ), 'A copy loaded before the stored progress moved is refused' );
+		$this->assertSame( 400, ImportSession::load( 84, $session->token() )->byte_offset(), 'The stale copy cannot replace newer progress' );
+
+		add_filter(
+			'pre_update_option__transient_wc_fulfillment_import_84_' . $session->token(),
+			function ( $value, $old ) {
+				unset( $value );
+				return $old;
+			},
+			10,
+			2
+		);
+		$this->assertFalse( $session->record_chunk( 10, $this->chunk_result( 5, 1, 650 ) ), 'A lost write is reported' );
+		$this->assertSame( 10, $session->processed(), 'A lost write does not advance the session in memory' );
+
+		$gone = $this->make_session( 85 );
+		$gone->delete();
+		$this->assertFalse( $gone->record_chunk( 0, $this->chunk_result( 5, 1, 650 ) ), 'A deleted session is refused' );
+		$this->assertNull( ImportSession::load( 85, $gone->token() ), 'A refused chunk does not bring the session back' );
+	}
+
+	/**
+	 * @testdox freeze_run_settings() stores the first mapping and options and keeps them.
+	 */
+	public function test_freeze_run_settings_keeps_the_first_settings(): void {
+		$mapping = array(
+			0 => 'order_number',
+			1 => 'tracking_number',
+			2 => 'shipment_provider',
+		);
+		$session = $this->make_session( 83 );
+
+		$this->assertTrue( $session->freeze_run_settings( $mapping, true, false ) );
+		$this->assertTrue( ImportSession::load( 83, $session->token() )->freeze_run_settings( array( 0 => 'tracking_number' ), false, true ) );
+
+		$reloaded = ImportSession::load( 83, $session->token() );
+		$this->assertSame( $mapping, $reloaded->frozen_mapping(), 'The first settings are stored and a second call keeps them' );
+		$this->assertTrue( $reloaded->notify_customer() );
+		$this->assertFalse( $reloaded->update_existing() );
+	}
+
+	/**
+	 * @testdox freeze_run_settings() rolls back a lost write, builds on a newer stored copy and refuses a deleted session.
+	 */
+	public function test_freeze_run_settings_writes_only_on_top_of_the_stored_session(): void {
+		$mapping = array( 0 => 'order_number' );
+		$session = $this->make_session( 86 );
+		$keep    = function ( $value, $old ) {
+			unset( $value );
+			return $old;
+		};
+		add_filter( 'pre_update_option__transient_wc_fulfillment_import_86_' . $session->token(), $keep, 10, 2 );
+		$this->assertFalse( $session->freeze_run_settings( $mapping, true, true ), 'A lost write is reported' );
+		remove_filter( 'pre_update_option__transient_wc_fulfillment_import_86_' . $session->token(), $keep, 10 );
+		$this->assertTrue( $session->freeze_run_settings( $mapping, true, true ) );
+		$this->assertSame( $mapping, ImportSession::load( 86, $session->token() )->frozen_mapping(), 'A retry stores the settings' );
+
+		$first  = $this->make_session( 87 );
+		$second = ImportSession::load( 87, $first->token() );
+		$first->freeze_run_settings( $mapping, true, true );
+		$first->record_chunk( 0, $this->chunk_result( 10, 7, 400 ) );
+		$this->assertTrue( $second->freeze_run_settings( array( 0 => 'tracking_number' ), false, false ) );
+		$reloaded = ImportSession::load( 87, $first->token() );
+		$this->assertSame( $mapping, $reloaded->frozen_mapping(), 'A stale copy does not replace the stored settings' );
+		$this->assertSame( 10, $reloaded->processed(), 'A stale copy does not rewind the stored progress' );
+		$this->assertSame( $mapping, $second->frozen_mapping(), 'The stale copy takes the stored settings' );
+
+		$early = $this->make_session( 89 );
+		$late  = ImportSession::load( 89, $early->token() );
+		$early->freeze_run_settings( $mapping, true, false );
+		$this->assertTrue( $late->record_chunk( 0, $this->chunk_result( 10, 7, 400 ) ) );
+		$reloaded = ImportSession::load( 89, $early->token() );
+		$this->assertSame( $mapping, $reloaded->frozen_mapping(), 'A chunk recorded by an older copy keeps the stored settings' );
+		$this->assertTrue( $reloaded->notify_customer() );
+		$this->assertFalse( $reloaded->update_existing() );
+		$this->assertSame( 10, $reloaded->processed() );
+
+		$gone = $this->make_session( 88 );
+		$gone->delete();
+		$this->assertFalse( $gone->freeze_run_settings( $mapping, true, true ), 'A deleted session is refused' );
+		$this->assertNull( ImportSession::load( 88, $gone->token() ) );
+	}
 }