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,
    rawExp.obs_mode,
    distTarget.target_id,
    distTarget.clean
FROM stackRun
JOIN stackInputSkyfile using(stack_id)
JOIN warpRun USING(warp_id)
JOIN fakeRun USING(fake_id)
JOIN camRun USING(cam_id)
JOIN chipRun USING(chip_id)
JOIN rawExp USING(exp_id)
JOIN distTarget ON distTarget.stage = 'stack' AND rawExp.obs_mode = distTarget.obs_mode
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'))
