What happens to .blk files on disk when the Bitcoin daemon switches to a longer chain? I’m interested in writing a program that will (1) parse the .blk files that my full-node Bitcoin daemon writes to disk and (2) write them to a relational database in an incremental fashion (i.e., keeping tracking of which .blk files I’ve already seen to avoid duplicating work). But it seems that this approach could lead to problems when my Bitcoin daemon says “uh-oh, another chain is bigger than the chain we currently have, let’s switch to it.” Specifically, I could imagine two possibilities:


The Bitcoin daemon goes back into an existing .blk file and deletes the blocks from the old chain. If that’s what happens, my program would need to keep track of the mtime of the .blk files on disk and overwrite the parsed data that was sourced from those .blk files when the mtime changes.
The Bitcoin daemon never modifies “finished” .blk files (i.e., block files other than the latest one that’s currently being written to), but rather knows that some of the blocks inside the .blk files could correspond to rejected blockchains. If this is the case, my program would need to query the daemon for this information and update the destination database appropriately.


Which (if either) of those possibilities is correct?
The second is correct. The blk*.dat files are append only. Once a block is downloaded and written to disk, it is never deleted (except when pruning). A block index (database) is maintained in blocks/index to keep track of block locations on disk and statuses (valid, invalid, etc.).