We noticed that returning a purchase order doesn't change the stock of the right item.
It turned out to be due to this lines of code:
$product_id = $delivery_item->get_variation_id() ?? $delivery_item->get_product_id();
$product_id = $po_item->get_variation_id() ?? $po_item->get_product_id();
get_variation_id() returned 0, and ?? is null coelescing, so it takes the first option if 0.
After changing to
$product_id = $delivery_item->get_variation_id() ? $delivery_item->get_variation_id() : $delivery_item->get_product_id();
$product_id = $po_item->get_variation_id() ? $po_item->get_variation_id() : $po_item->get_product_id();
The same scenario resulted the expected stock change.