WITH cte AS (
SELECT *,
SUM((flag IS NULL) :: INT) OVER (PARTITION BY user_id ORDER BY product_id ASC) grp
FROM test
)
SELECT product_id, user_id, flag,
DENSE_RANK() OVER (PARTITION BY user_id ORDER BY grp ASC) "rank"
FROM cte
ORDER BY 1,2;