SELECT DISTINCT
    'stack' as stage,
    stackRun.stack_id AS stage_id,
    -- run tag in the form 'stack.$skycell_id.$stack_id'
    CONCAT_WS('.', 'stack', stackRun.skycell_id, convert(stackRun.stack_id, CHAR)) as run_tag,
    distTarget.label,
    distTarget.target_id,
    distTarget.clean
FROM stackRun
JOIN distTarget ON distTarget.stage = 'stack'
    AND stackRun.label = distTarget.label
    AND stackRun.filter = distTarget.filter
JOIN rcInterest USING(target_id)
LEFT JOIN distRun ON distRun.stage = 'stack' AND (distRun.stage_id = stack_id)
    AND distRun.clean = distTarget.clean
    -- JOIN hook %s
WHERE  distTarget.state = 'enabled'
    AND rcInterest.state = 'enabled'
    AND distRun.dist_id IS NULL
    AND ((stackRun.state = 'full') OR (distTarget.clean AND stackRun.state = 'cleaned'))
