Backport some changes from record-schedule branch to fix a bug.