How is over-spending one block apart prevented? So, let's say you have a wallet with 20BTC, and you have a flow like so:


You send 15BTC to A in block 1
You send 15BTC to B in block 2


What happens if at block 1 there are two chains across miners. In chain X the transaction is there, in chain Y, the transaction is not there. 

When they go to spend the other 15BTC in block 2 and their wallet(imagine a different computer using the same wallet) is on chain Y, then their wallet will let them do it. What happens when: 


Chain X becomes the dominant chain
** Transaction 1 would have confirmed, so would transaction 2 have been rejected and never confirm?  
Chain Y becomes the dominant chain
** Transaction 2 would have confirmed, so would transaction 1 be rejected and never confirm? 


How is this represented in the bitcoin software even? I know there are some transactions that can be broadcast but then never confirmed, but how does the wallet know the money is not spend if it's been broadcast?
When a node learns of a transaction, some validity tests are performed and if the transaction is not yet in the blockchain it knows of with the longest height and the transaction also is valid (i.e., not a double spend) then that transaction is added to that node's memory pool.

If a later transaction arrives at a node but is an attempt to double spending of a transaction that is either already in the blockchain with the longest height or is already in the memory pool, then that later transaction is ignored.

A transaction propagates to nearly all miners within seconds, so most miners would immediately reject your later double-spend attempt since they would already know of the earlier transaction.

Blockchain forks happen all the time (i.e., multiple times each day).  So it is entirely possible to have conflicts where a transaction is included in a block on one side of the fork but is not yet in the block (or blocks) on the other side of the fork.  Eventually one of the several competing blockchain forks will emerge as the longest chain and the transactions in that chain are the ones reflected in the Bitcoin ledger from then on.  That's why exchanges wait until three or six confirmations -- as it is technically possible for there to be variations between sides should a fork occur.

Attackers might use this temporary inconsistency in an attempt to defraud by employing a race attack or other approach.  This is requisite reading on the topic: http://en.bitcoin.it/wiki/Double-spending