Obviously, the algorithm that you present probably is not the real one, but this simply looks to me like something that ought to be able to benefit from sorting and/or grouping on the database level. Is there truly nothing that you can do in that query in order to produce aggregated results? Also: you still must have a breakdown of the timing, even if you simply print the time-of-day to STDERR at the point at which the query-prepare is finished and the point at which the first row of data is produced. I’ve got several terabytes of data storage on my computer right here, and even though it takes a while to move that much data around, and even though it’s not squirting through a large TCP/IP network, I don’t believe for a second that “16 days” can’t be very significantly improved upon.
You should also, just to be sure, explain that query (since it doesn’t use the verb inner join), to make sure that it’s not doing something absolutely insane such as a Cartesian product at any point. (16 days ... what would do that? Anything along those lines would. If there are no indexes, you probably just found your problem, and explain would confirm or deny it.)
Probably the number-one improvement would be any way whatsoever by which you can prevent all that data from being transmitted. The second would be to avoid a massive hash that must accumulate before its contents can be dumped. For instance, if the data were or could be indexed by what you call “marker,” then you could select distinct a list of those markers and process them one at a time, perhaps in parallel. It would no longer have to grind away for 16 days without producing anything and at the ever-present risk of producing nothing at all. If meaningful, it might be able to say, “I already have that file, and it looks like I don’t need to produce it again. (If the data were stored back in a table rather than a CSV, the server might be able to do that with the help of a join ... and the whole process might conceivably become the candidate for a stored-procedure or for a process running directly on the database-server, thereby avoiding across-the-network I/O.