Sorry. Both. I think your naming makes you think its right even though its not. You're searching a source seq against the target seq I think. The inconsistent variable naming is making that difficult to read through.

Here's the first pass at a refactoring I did:

https://github.com/cloudant/mem3/compare/21973-include-target-seq-in-checkpoint-davisp

I reworded the comment for this function here:

https://github.com/cloudant/mem3/blob/78a342777353a6b9c2f28fa84798efa489b1eec9/src/mem3_rep.erl#L106

Perhaps an example is in order. Given a shard copy pair on nodes A and B, during normal operation we have A doing push internal replications A -> B. Node A saves _local docs on B (and A, but that's unimportant for this dicussion). Those docs have "source_*" fields that refer to node A and "target_*" fields that refer to node B.

Some time passes and then we have a situation where A is broken and we get to the replacement logic. This executes on Node B. In the fabric area where you invoke this function you invoke it with:

SourceDb = couch_db:open_int(DbName, []),
TargetNode = A
TargetUuid = UUID from node A
TargetSeq = seq from node A

And then you search this against the "target_*" fields in the history info. So you're comparing values from A against values written for B.

In my refactor you'll see I switched variable names as well as matching against the "source_*" fields so that A values are matched against A values, and then I return the target_seq field so that we know where to resume from. I could also be reading things wrong. It is kinda subtle.