In Magento, you can customize the sequence in which totals are calculated during the checkout process by specifying the order in which each total should be processed. This is done by using the before and after attributes in your configuration.

When adding a custom total, it’s crucial to ensure that the sorting rules do not conflict with existing totals. For instance, if you define a custom total such as shippingprotectiontax, you might encounter an issue where tax_shipping appears before shipping, leading to the shipping tax being applied twice. This contradicts the intended rule:

<shippingprotectiontax>
    <class>n98_shippingprotection/quote_address_total_shippingprotectionTax</class>
    <after>subtotal,discount,shipping,tax</after>
    <before>grand_total</before>
</shippingprotectiontax>

To troubleshoot sorting issues, you can examine the sorted array returned by the usort function in the Mage_Sales_Model_Quote_Address_Total_Collector::_getSortedCollectorCodes() method. The following callback function is responsible for comparing totals:

/**
 * uasort callback function
 *
 * @param   array $a
 * @param   array $b
 * @return  int
 */
protected function _compareTotals($a, $b) {
    $aCode = $a['_code'];
    $bCode = $b['_code'];
    if (in_array($aCode, $b['after']) || in_array($bCode, $a['before'])) {
        return -1;
    } elseif (in_array($bCode, $a['after']) || in_array($aCode, $b['before'])) {
        return 1;
    }
    return 0;
}

After sorting, you can log the results to verify the order:

protected function _getSortedCollectorCodes() {
    // ...
    uasort($configArray, array($this, '_compareTotals'));
    Mage::log('Sorted:');
    $loginfo = "";
    foreach($configArray as $code => $data) {
        $loginfo .= "$code\n";
        $loginfo .= "after: ".implode(',', $data['after'])."\n";
        $loginfo .= "before: ".implode(',', $data['before'])."\n\n";
    }
    Mage::log($loginfo);
    // ...
}

By carefully reviewing the output of your logs, you can identify any discrepancies in the sorting rules that may be causing unexpected behavior in the total calculations.