If you have stackable items with different components (custom_data, or custom_model_data) in you inventory. The stacks will merge when you select a villager trade that accepts the base item.
Reproductions:
Spawn a librarian villager.
Get emeralds and two books a vanilla one without custom components and one with
/give @p minecraft:book[minecraft:custom_data={Test:1b}]
Select a trade for an echanted book
The two books will be merged into one stack
Can confirm