The bug
When a villager with custom trade is created which requires the same type of item in both slots, but with differing NBT data, and then specific (see example below) quantities of those items are provided but in reverse order, the villager will pickup the wrong items when being traded with.
How to reproduce
Create a villager with a custom trade like this:
/summon villager ~1 ~ ~ {Offers:{Recipes:[{buy:{id:"paper",Count:5,tag:{display:{Lore:["A"]}}},buyB:{id:"paper",Count:1,tag:{display:{Lore:["B"]}}},maxUses:9999999,sell:{id:"stone",Count:1},rewardExp:false}]}}
→ The villager now requires: Item1: x5 paper lore:A, Item2: x1 paper lore:B
Insert the following items in the trading menu: Slot1: x5 paper lore:B, Slot2: x5 paper lore:A
/give @s paper{display:{Lore:["A"]}} 5 /give @s paper{display:{Lore:["B"]}} 5
→ The villager will allow the trade
Pickup the result item.
→ Resulting items remaining in the trading menu: Slot1: empty, Slot2: x4 paper lore:A
→ It has picked up 4 additional items with lore B, but left 4 items with lore A (which he should have taken instead)
Code analysis
Based on 1.12.2 decompiled using MCP 9.40
The method net.minecraft.inventory.SlotMerchantResult.doTrade(MerchantRecipe, ItemStack, ItemStack)
does not check for the NBT data of the items.
Confirmed for 1.13.1.