Terminate_after with aggregation

I want to know how aggregation behaves when combined with terminate_after.
Is it that first the aggregations are performed from records belonging to all shards and then terminate_after setting are applied
first the records are collected based on terminate_after from each shard and then aggregation is applied.

Also, if it works the first way, then is it possible that lesser number of buckets are returned in the result than the actual number of buckets from all the shards