The federal bank iterates through all of the records in the file and attempts to perform each transaction using the pair of account info, the type of transaction, and the details in the transaction record.
To answer the question about why it takes so long?
Generally it doesn't actually. Most companies will tell you it takes 24hrs to send you money, and that's because most companies generate and submit an ACH file once a day, and the federal bank will process those files at some point after that.
Why does it take weeks for a deposit to be marked invalid and reversed? Well, analytics, fraud detection, and those kinds of activities are not all real-time. More than you think are actually caught _remarkably_ fast, but many take time to find and often include collaboration with multiple banks, government agencies, and policing organizations from multiple countries. That means geo-political concerns, international treaties, timezones, communication problems. You name it.