#!/bin/sh
#
# Copyright (C) 2003 - 2026 Qore Technologies, s.r.o.
#
# Plan one AOT object group's incremental rebuild before per-object recipes run.
#
# A broad invalidation must not enter the build as hundreds of recursive
# qore-qo-incremental processes: those processes traverse the same predecessor
# closure and then occupy jobserver slots while waiting on the same component
# locks.  This coordinator performs one group-wide currency pass first.  Small
# stale sets retain the standalone compile path; broad sets use one shared parse
# whose LLVM emission workers participate in the caller's jobserver.

set -eu

if [ "$#" -ne 8 ]; then
    echo "usage: $0 CONTEXT PLAN_STAMP BOOTSTRAP_STAMP BATCH_SCRIPT SINGLE_SCRIPT SOURCE_ORDER_HELPER INCREMENTAL_HELPER BATCH_BOOTSTRAP_HELPER" >&2
    exit 2
fi

context=$1
plan_stamp=$2
bootstrap_stamp=$3
batch_script=$4
single_script=$5
source_order_tool=$6
incremental_tool=$7
batch_bootstrap_tool=$8
stale_file=

run_source_order() {
    if [ -n "${QORE_QCC_QORE_EXECUTABLE:-}" ] \
            && [ -x "$QORE_QCC_QORE_EXECUTABLE" ]; then
        "$QORE_QCC_QORE_EXECUTABLE" "$source_order_tool" "$@"
    else
        "$source_order_tool" "$@"
    fi
}

cleanup() {
    if [ -n "$stale_file" ]; then
        rm -f "$stale_file" "$stale_file.rows" "$stale_file.keys" \
            "$stale_file.order" "$stale_file.components" "$stale_file.pending" \
            "$stale_file.preload"
    fi
    if [ -n "$subset_plan_file" ]; then
        rm -f "$subset_plan_file"
    fi
    if [ -n "$subset_deferred_file" ]; then
        rm -f "$subset_deferred_file"
    fi
}
trap cleanup EXIT
trap 'exit 1' HUP INT TERM

for required in "$context" "$batch_script" "$single_script"; do
    if [ ! -f "$required" ]; then
        echo "$0: missing incremental-plan input: $required" >&2
        exit 1
    fi
done
for helper in "$source_order_tool" "$incremental_tool" "$batch_bootstrap_tool"; do
    if [ ! -x "$helper" ]; then
        echo "$0: missing incremental-plan helper: $helper" >&2
        exit 1
    fi
done

# The stale-component count at which compiling one at a time stops paying.
#
# A standalone compile preloads every other member of the group to resolve its
# cross-file references, so N standalone compiles read the group N times; one
# shared parse over the same N sources reads it once.  The boundary is therefore
# low: two stale components already pay for the shared parse.  It was 8 while
# "shared parse" could only mean the WHOLE group, where the trade was 8 compiles
# against reparsing hundreds of current sources.
batch_threshold=${QORE_QCC_INCREMENTAL_BATCH_THRESHOLD:-2}
case "$batch_threshold" in
    ''|*[!0-9]*|0)
        echo "$0: QORE_QCC_INCREMENTAL_BATCH_THRESHOLD must be a positive integer" >&2
        exit 2
        ;;
esac

# When the rebuild closure is so much of the group that parsing the group is the
# same work, expressed as a percentage of the group's components.
#
# The threshold above used to select the WHOLE-GROUP parse, which made it a
# cliff: a group of 813 components sent one edit with 13 consumers through a
# reparse of all 868 sources.  The closure decides only this question now --
# whether to skip the subset parse and reparse everything -- and it scales with
# the group, so a small group still reaches the whole-group parse early while a
# large one does not reparse hundreds of current sources to rebuild ten.
#
# Its default depends on what serves the band below it, because that is what the
# closure is being compared against:
#
#   * with a partial parse, the band below is ONE parse over the stale set, and
#     the group's own parse is worth reaching for only when the closure really is
#     most of the group; and
#   * without one, the band below is a walk of standalone compiles, run one
#     component at a time, each preloading the whole group.  The group's own
#     parse compiles every member in one parse and at the build tool's
#     parallelism, so it overtakes the walk early.
#
# What decides the crossover is not one build but the next one.  The group's
# parse and a standalone compile publish different compile contracts for the
# same source, so the first incremental build after a group parse walks the
# whole closure of whatever was edited whatever the size of the edit -- and a
# build that escalates leaves the tree in the mode that makes the NEXT edit walk
# it again.  A walk pays that transition once and every edit after it is one
# compile.  Measured on Qorus (875 sources, 820 components), editing a source
# whose closure is 13: the walk and the group parse cost the same on the first
# build (5m03 against 4m54), and the second edit costs 1m38 against another
# 4m54.  So the floor should sit well above the closures a developer edits
# through, and only catch the ones a walk could never amortise: at 408
# components, a walk is an hour of serial compiles against a four-minute parse.
#
# 5% puts that boundary at 41 components on that tree.  Left at 50% the floor
# was 410, and thirteen widely required sources sat at closures of 408 and 409 --
# exactly the ones the walk cannot amortise.  Set the variable to pin either
# value.
group_batch_percent=${QORE_QCC_INCREMENTAL_GROUP_BATCH_PERCENT:-}
group_batch_minimum=${QORE_QCC_INCREMENTAL_GROUP_BATCH_MINIMUM:-8}
case "$group_batch_minimum" in
    ''|*[!0-9]*|0)
        echo "$0: QORE_QCC_INCREMENTAL_GROUP_BATCH_MINIMUM must be a positive integer" >&2
        exit 2
        ;;
esac
case "$group_batch_percent" in
    '')
        ;;
    *[!0-9]*)
        echo "$0: QORE_QCC_INCREMENTAL_GROUP_BATCH_PERCENT must be an integer" >&2
        exit 2
        ;;
esac
subset_script=${QORE_QCC_SUBSET_SCRIPT:-}
subset_plan_file=
subset_deferred_file=
# stale components the last shared parse of the stale set left for the next pass
subset_deferred=0

mkdir -p "$(dirname "$plan_stamp")"
stale_file=$(mktemp "${TMPDIR:-/tmp}/qore-qo-incremental-plan.XXXXXX")

# The dependency graph this plan is scheduled against.
#
# A compile rewrites its own depfile, qore-qo-source-order promotes depfile
# entries to required edges, and those edges decide component membership,
# numbering, preload closures and publication targets.  Reading them live means
# every helper process sees a different graph, so a plan resolved before a
# compile can no longer be executed after it -- and that is true of this
# coordinator's own serial loop, not only of the parallel object recipes that
# follow it.
#
# Freezing the edge set makes the graph immutable for the whole phase.  The
# freeze itself must see the live depfiles, so it happens only here, between
# phases, with no compile in flight; the whole-group batch runs with no snapshot
# because it holds the group lock and rewrites every depfile in the group.
graph_snapshot=${QORE_QCC_GRAPH_SNAPSHOT:-$context.graph-snapshot.json}

# A variable assignment written as a prefix to a SHELL FUNCTION may outlive the
# call, so each of these sets the snapshot inside a subshell instead; only an
# external command's prefix assignment is reliably scoped to that command.
freeze_graph() {
    # The batch stamp names the whole-group publication the frozen edge set was
    # read from; the helper dates it by the publication sidecar beside the stamp,
    # never by the stamp, which recipes that publish nothing also touch.  The
    # snapshot is a plain file that outlives this build, so without that date a
    # recipe the build tool schedules ahead of the next build's first freeze --
    # which any target depending on the object stamps rather than on the group's
    # order targets is free to do -- applies the previous build's graph, and its
    # publication is then refused as a graph transition.
    frozen=$(
        QORE_QCC_GRAPH_SNAPSHOT=
        export QORE_QCC_GRAPH_SNAPSHOT
        run_source_order --scc-freeze-graph "$graph_snapshot" \
            --batch-stamp "$bootstrap_stamp" "$context"
    ) || return 1
    echo "$0: scheduling against dependency graph $frozen"
}

write_stale_plan() {
    (
        QORE_QCC_GRAPH_SNAPSHOT=$graph_snapshot
        export QORE_QCC_GRAPH_SNAPSHOT
        run_source_order --scc-source-stale --rebuild-closure --all-members \
            --batch-stamp "$bootstrap_stamp" "$context"
    ) > "$stale_file"
    # Rows are members; components are the unit of work, and one shared parse
    # over the stale set needs every member of every one of them.
    stale_count=$(awk -F '\t' '$1 != "rebuild-closure" && !seen[$2]++ { rows++ }
        END { print rows + 0 }' "$stale_file")
    # The component keys of the stale set, in one comparable string.  A pass that
    # compiles its whole stale set and finds the same set stale again has not
    # moved, and no number of further passes will move it; the group's own parse
    # is the answer to that, not another lap.
    stale_signature=$(awk -F '\t' '$1 != "rebuild-closure" { print $2 }' \
        "$stale_file" | sort -u | tr '\n' ' ')
    # How much of the group the stale set will actually reach once it is
    # rebuilt.  Absent only if the helper predates the row, in which case the
    # stale count is the best available answer and the old behaviour stands.
    rebuild_scope=$(awk -F '\t' '$1 == "rebuild-closure" { print $2; exit }' \
        "$stale_file")
    case "$rebuild_scope" in
        ''|*[!0-9]*)
            rebuild_scope=$stale_count
            ;;
    esac
    group_components=$(awk -F '\t' '$1 == "rebuild-closure" { print $3; exit }' \
        "$stale_file")
    case "$group_components" in
        ''|*[!0-9]*|0)
            group_components=0
            ;;
    esac
    # The closure that makes the whole-group parse the cheaper answer: it is only
    # cheaper when the parse would preload objects it is about to replace anyway.
    #
    # The absolute floor is the value this scheduler has always used, so a small
    # group behaves as it did; the scaled floor is what keeps a large one from
    # reparsing 868 sources to rebuild a closure of thirteen.
    group_batch_floor=$group_batch_minimum
    if [ "$group_components" -gt 0 ]; then
        scaled=$(( (group_components * group_batch_percent + 99) / 100 ))
        if [ "$scaled" -gt "$group_batch_floor" ]; then
            group_batch_floor=$scaled
        fi
    fi
}

#! True when a stale row names a component that spans several sources.
#  Such a component has no valid internal order, so only the shared parse can
#  compile it whatever the rest of the plan looks like.
stale_plan_has_multi_member_component() {
    awk -F '\t' '$1 != "rebuild-closure" && $3 > 1 { found = 1 }
        END { exit !found }' "$stale_file"
}

#! One shared parse over the stale set, preloading everything it does not compile.
#  This is the answer for every invalidation that is too wide for standalone
#  compiles and too narrow to be worth reparsing the group: a component that spans
#  several sources (which has no standalone builder at all), and a stale set of
#  several components (which as standalone compiles pays the sibling-preload cost
#  once per source).
#! True when this group can parse part of itself in one go.
#  A subset parse publishes exactly what a standalone compile of the same source
#  publishes -- same object, same compile contract -- because both resolve their
#  cross-member references against preloaded `.qo` shells.  It is the standalone
#  path's semantics with the standalone path's per-source preload cost paid once
#  for the whole stale set.  A consumer configured by an older QoreMacros.cmake
#  has no subset script, and QORE_QCC_SUBSET_PARSE=0 declines it explicitly.
#  Opt-in with QORE_QCC_SUBSET_PARSE=1.  A parse that resolves part of a group
#  against preloaded shells cannot see the bodies the group's own parse sees, so
#  the objects it emits record fewer cross-object fast-entry providers -- the same
#  difference the standalone path has always had, but now reachable for sources
#  that used to be compiled only by the group's parse.  Until that difference is
#  either closed or accepted deliberately, the scheduler keeps the shape it had.
have_subset_parse() {
    [ "${QORE_QCC_SUBSET_PARSE:-0}" = 1 ] && [ -n "$subset_script" ] \
        && [ -f "$subset_script" ]
}

run_subset_batch() {
    subset_plan_file=$(mktemp "${TMPDIR:-/tmp}/qore-qo-subset-plan.XXXXXX")
    # The parse compiles only the part of the stale set it can compile consistently and
    # names the rest here; they stay stale and the next pass compiles them.
    subset_deferred_file=$(mktemp "${TMPDIR:-/tmp}/qore-qo-subset-deferred.XXXXXX")
    awk -F '\t' '$1 != "rebuild-closure" && NF >= 5 { print $2 "\t" $4 "\t" $5 }' \
        "$stale_file" > "$subset_plan_file"
    echo "$0: $stale_count stale component(s) of $group_components; compiling them" \
        "together and preloading the rest of the group"
    # No snapshot: the parse holds the group lock and rewrites the depfile of
    # every member it compiles, so it must publish against the graph its own
    # compiles produce -- the same rule the whole-group parse follows.
    QORE_QCC_GRAPH_SNAPSHOT= \
    QORE_QCC_SUBSET_PLAN="$subset_plan_file" \
    QORE_QCC_SUBSET_SCRIPT="$subset_script" \
    QORE_QCC_SUBSET_DEFERRED="$subset_deferred_file" \
        QORE_QCC_QORE_EXECUTABLE="${QORE_QCC_QORE_EXECUTABLE:-}" \
        "$batch_bootstrap_tool" "$context" "$bootstrap_stamp" \
            "$batch_script" "$source_order_tool"
    subset_rc=$?
    subset_deferred=$(awk 'NF' "$subset_deferred_file" | wc -l | tr -d ' ')
    rm -f "$subset_plan_file" "$subset_deferred_file"
    subset_plan_file=
    subset_deferred_file=
    return $subset_rc
}

run_group_batch() {
    echo "$0: broad incremental invalidation; selecting the shared-parse batch"
    # No snapshot: the batch compiles every member of every component under the
    # group lock, so nothing can be reading a graph it invalidates, and the next
    # freeze records exactly the graph it published against.
    QORE_QCC_GRAPH_SNAPSHOT= \
    QORE_QCC_FORCE_BATCH=1 \
    QORE_QCC_REQUIRE_BATCH=1 \
        QORE_QCC_QORE_EXECUTABLE="${QORE_QCC_QORE_EXECUTABLE:-}" \
        "$batch_bootstrap_tool" "$context" "$bootstrap_stamp" \
            "$batch_script" "$source_order_tool"
}

# have_subset_parse() answers for this group and this environment, so the
# escalation percentage cannot be resolved with the other knobs at the top of
# the script.
if [ -z "$group_batch_percent" ]; then
    if have_subset_parse; then
        group_batch_percent=50
    else
        group_batch_percent=5
    fi
fi

#! Names the components of the current stale plan, one per line, with a source.
#  A post-condition that reports only that components are stale leaves whoever
#  is triaging it with nothing to look at: the message names no component, no
#  source and no line, so it cannot be told apart from a parse error without
#  reconstructing the plan by hand.  The component key is what every other
#  helper addresses a component by, and one of its members locates it in the
#  tree.
report_stale_components() {
    awk -F '\t' '$1 != "rebuild-closure" && !seen[$2]++ {
            printf "    %s (%d source(s), including %s)\n", $2, $3, $4
        }' "$stale_file" >&2
}

#! True when component KEY, row ROW of this pass, preloads a row the pass has yet to compile.
#  The rows are ordered so that every compile follows the stale components it
#  preloads, which leaves this possible only inside a cycle of content
#  dependencies: no order serves every member of one, so a member compiled
#  first reads a peer's previous object.  A failure there may be the peer's
#  stale declarations rather than the source's own error, and only the group's
#  own parse, which preloads nothing, can tell the two apart.
preloads_pending_component() {
    awk -F '\t' -v row="$2" 'NR > row && $5 != "" { print $5 }' \
        "$stale_file.components" > "$stale_file.pending"
    if [ ! -s "$stale_file.pending" ]; then
        return 1
    fi
    # The loop that calls this reads its rows from standard input.
    if ! (
        QORE_QCC_GRAPH_SNAPSHOT=$graph_snapshot
        export QORE_QCC_GRAPH_SNAPSHOT
        run_source_order --scc-preload "$context" "$1"
    ) < /dev/null > "$stale_file.preload"; then
        echo "$0: cannot read the preload set of stale component $1" >&2
        return 1
    fi
    grep -Fxq -f "$stale_file.pending" "$stale_file.preload"
}

#! Records what the group now reads from outside itself, for the next build.
#  The build tool watches those inputs through one depfile on the group's
#  external-input stamp, which the bootstrap depends on: a move in any of them
#  reaches the bootstrap's currency check, and it hands the components that read
#  it to this coordinator.  Written at the end of a plan because the plan's
#  compiles are what add to the set -- a standalone compile is the only record of
#  a module a member started requiring after the group's last shared parse.  A
#  group configured by an older QoreMacros.cmake names no stamp.
record_external_inputs() {
    if [ -z "${QORE_QCC_EXTERNAL_INPUTS_STAMP:-}" ]; then
        return 0
    fi
    run_source_order --scc-external-inputs "$QORE_QCC_EXTERNAL_INPUTS_STAMP" \
        "$context"
}

#! The group's own parse, then the verification every plan ends with.
#  The batch rewrote every depfile in the group, so the frozen generation no
#  longer describes it.  Re-freeze before verifying, and leave the object
#  recipes that follow this target the graph the batch published against rather
#  than the one it superseded.
escalate_to_group_batch() {
    run_group_batch
    freeze_graph || exit 1
    write_stale_plan
    if [ "$stale_count" -ne 0 ]; then
        echo "$0: shared-parse incremental build left $stale_count stale" \
            "component(s):" >&2
        # A diagnostic decides nothing, so it must not be able to change what
        # this reports: under `set -e` a failure inside it would end the script
        # with its own status instead of the one below.
        report_stale_components || :
        exit 1
    fi
    record_external_inputs || exit 1
    touch "$plan_stamp"
    exit 0
}

# One pass compiles the stale set it was planned from, and compiling a component
# rewrites its compile contract, so the pass leaves that component's consumers
# stale: an invalidation walks the consumer closure one dependency level per
# pass, and the plan converges only when it has walked all of them.  The loop
# therefore runs until the group is current rather than for a fixed number of
# passes.  A fixed two was a cliff of its own: the first incremental build after
# a whole-group parse walks a closure several levels deep -- the objects the
# group's parse emitted record different compile contracts from the ones a
# standalone or subset compile emits, so the whole closure is crossed once --
# and capping the walk at two passes threw a converging plan away and reparsed
# the group.  Measured on Qorus (875 sources, 820 components), `make qorus-core`
# after one comment appended to a source whose closure is thirteen: three passes
# and 23 qcc invocations, 4m52, where the capped loop ran 889 and took 7m39.
#
# Two conditions end the walk early, and both mean the same thing -- the
# incremental path is no longer the cheaper answer:
#
#   * a pass that leaves exactly the stale set it started from has not moved,
#     and no further pass will move it; and
#   * a walk whose compiles have added up to what the whole-group parse would
#     have compiled anyway has spent the group parse's budget without its
#     parallelism.
#
# The second is also what bounds the loop: every pass compiles at least one
# component, so the cumulative count reaches the bound in a finite number of
# passes whatever the graph does.
#
# Each pass begins by freezing the graph, so a pass is planned, executed and
# verified against one immutable decomposition, and a new required edge that a
# compile discovered is crossed at a defined point rather than mid-pass.
compiled_total=0
previous_signature=
phase=1
while :; do
    freeze_graph || exit 1
    write_stale_plan
    if [ "$stale_count" -eq 0 ]; then
        record_external_inputs || exit 1
        touch "$plan_stamp"
        exit 0
    fi

    # The batch decision is made from the rebuild CLOSURE, never from the stale
    # set.  Compiling a component rewrites its compile contract, so every
    # component that consumes it goes stale as a result -- which means the stale
    # set is the work this pass starts with and the closure is the work the
    # build ends up doing.  Deciding from the stale set let one edited widely
    # required source look like a one-component job: the standalone path
    # compiled it alone, on one core, and the next pass then found the whole
    # group stale and ran the shared parse anyway, recompiling what had just
    # been built.  Nothing reported the wasted serial pass, because from inside
    # it the plan looked small.
    # Three answers, in order of how much of the group each one parses.
    #
    # The closure -- not the stale set -- decides whether to parse the whole
    # group, because compiling a component rewrites its compile contract and
    # every consumer of it goes stale as a result: a closure that covers most of
    # the group will be compiled either way, and one parse is cheaper than two
    # passes over the same sources.  Below that, the stale set decides between
    # one shared parse and standalone compiles, and a component that spans
    # several sources always needs a parse: its members are mutually dependent
    # and have no valid internal order.
    if [ "$rebuild_scope" -ge "$group_batch_floor" ]; then
        escalate_to_group_batch
    fi

    # A pass that changed nothing, and a walk that has already compiled what the
    # group parse would have compiled: see the loop's comment.  Both are stated
    # rather than silent -- a build that quietly reparses the group after doing
    # the incremental work as well is otherwise indistinguishable from one that
    # simply chose the group parse.
    if [ "$stale_signature" = "$previous_signature" ]; then
        echo "$0: pass $phase left the same $stale_count component(s) stale that" \
            "it compiled; the incremental plan is not converging" >&2
        escalate_to_group_batch
    fi
    previous_signature=$stale_signature
    if [ "$(( compiled_total + stale_count ))" -gt "$group_batch_floor" ]; then
        echo "$0: the incremental plan has compiled $compiled_total component(s)" \
            "over $(( phase - 1 )) pass(es) and $stale_count remain; that is the" \
            "work the group's own parse does, without its parallelism" >&2
        escalate_to_group_batch
    fi
    if stale_plan_has_multi_member_component \
            || { have_subset_parse && [ "$stale_count" -ge "$batch_threshold" ]; }; then
        # A component that spans several sources has no standalone builder at
        # all, so it needs a shared parse whether or not this group can parse
        # part of itself; everything else falls back to compiling one component
        # at a time, which is what this scheduler did before partial parses
        # existed.
        if have_subset_parse; then
            if run_subset_batch; then
                subset_rc=0
            else
                subset_rc=$?
            fi
            # 76 is a dependency-graph transition, not a failure: another builder
            # -- an object recipe a consumer scheduled without waiting for this
            # target -- compiled a member while the parse was running, so the
            # decomposition the parse resolved its components against no longer
            # names them.  The next pass freezes the graph again and re-plans
            # against what is now there, which is the whole point of the loop.
            if [ "$subset_rc" -eq 76 ]; then
                echo "$0: the dependency graph moved while the stale set was" \
                    "compiled; re-planning against the graph it left"
            elif [ "$subset_rc" -ne 0 ]; then
                # A parse of part of a group resolves the members it did not
                # compile from their `.qo` shells, and a shell can carry a
                # declaration the parse itself makes -- an enum declared in one
                # source and folded into another comes back through the second
                # source's object, and the first source can then no longer
                # declare it.  The group's own parse has no shells and so no such
                # conflict; it is the answer this build would have used before
                # partial parses existed, and reaching for it keeps a build that
                # works today working.
                echo "$0: the shared parse of the stale set failed; falling back" \
                    "to the group's own parse" >&2
                # the group's parse compiles everything, including what the failed parse left out
                subset_deferred=0
                if ! run_group_batch; then
                    echo "$0: shared parse of the group failed" >&2
                    exit 1
                fi
            fi
        elif stale_plan_has_multi_member_component; then
            if ! run_group_batch; then
                echo "$0: shared parse of the group failed" >&2
                exit 1
            fi
        fi
        # The parse rewrote the depfiles of everything it compiled, so the frozen
        # generation no longer describes the graph; the loop's next pass freezes
        # again and picks up whatever the compiles made stale -- and what a shared
        # parse of the stale set left for it, which it did not compile.
        compiled_total=$((compiled_total + stale_count - subset_deferred))
        subset_deferred=0
        phase=$((phase + 1))
        continue
    fi

    # Standalone compiles run one after another in this loop, so the count and
    # the reason for choosing it are worth stating: a build that quietly serialises
    # on a many-core host is otherwise indistinguishable from one that is simply
    # slow.
    if have_subset_parse; then
        echo "$0: compiling $stale_count stale component(s) incrementally, one at a" \
            "time; their consumer closure spans $rebuild_scope component(s), under" \
            "the QORE_QCC_INCREMENTAL_BATCH_THRESHOLD of $batch_threshold that" \
            "selects the shared parse"
    else
        # Naming the threshold here would be wrong: it was never consulted.  With
        # no partial parse available the only shared parse this group has is its
        # own, and that decision was already made from the closure.
        echo "$0: compiling $stale_count stale component(s) incrementally, one at a" \
            "time; their consumer closure spans $rebuild_scope component(s), and" \
            "this group has no partial parse to compile them together" \
            "(QORE_QCC_SUBSET_PARSE is off)"
    fi
    tab=$(printf '\t')
    # Each row was resolved from the graph as it stood before this loop began,
    # and every compile in the loop rewrites a depfile that contributes required
    # edges.  The component key survives that -- it names a member set -- while
    # the index does not, so the key is what the builder is given to address its
    # component with.
    awk -F '\t' '$1 != "rebuild-closure" && !seen[$2]++' "$stale_file" > "$stale_file.rows"
    # The stale listing is in topological order, which follows required edges
    # only.  A stale component can also preload another one over a content
    # dependency or a load requirement, and compiling it first would resolve it
    # against that provider's previous object -- a call to a signature changed in
    # the same edit then fails to parse.  So the rows are compiled in the order
    # the helper derives from everything each compile preloads.
    awk -F '\t' '{ print $2 }' "$stale_file.rows" > "$stale_file.keys"
    if ! (
        QORE_QCC_GRAPH_SNAPSHOT=$graph_snapshot
        export QORE_QCC_GRAPH_SNAPSHOT
        run_source_order --scc-order-set "$context" "$stale_file.keys"
    ) > "$stale_file.order"; then
        echo "$0: cannot order the $stale_count stale component(s) for" \
            "standalone compiles" >&2
        exit 1
    fi
    awk -F '\t' 'NR == FNR { row[$2] = $0; next } ($1 in row) { print row[$1] }' \
        "$stale_file.rows" "$stale_file.order" > "$stale_file.components"
    ordered_count=$(awk 'END { print NR + 0 }' "$stale_file.components")
    rm -f "$stale_file.rows" "$stale_file.keys" "$stale_file.order"
    if [ "$ordered_count" -ne "$stale_count" ]; then
        echo "$0: ordering the stale set returned $ordered_count of" \
            "$stale_count component(s)" >&2
        exit 1
    fi
    row=0
    while IFS="$tab" read -r component_index component_key component_size source output; do
        row=$((row + 1))
        [ -n "$component_key" ] || continue
        component_lock=$(dirname "$output")/.qcc-scc/$component_key.lock
        # `$?` after a NEGATED condition is the negation's status, not the builder's,
        # so the status is captured in the else branch.
        if QORE_QCC_PLANNED_STALE=1 \
                QORE_QCC_COMPONENT_INDEX="$component_index" \
                QORE_QCC_COMPONENT_KEY="$component_key" \
                QORE_QCC_COMPONENT_SIZE="$component_size" \
                QORE_QCC_COMPONENT_LOCK="$component_lock" \
                QORE_QCC_PREREQUISITES_READY=1 \
                QORE_QCC_BATCH_BOOTSTRAP_STAMP="$bootstrap_stamp" \
                QORE_QCC_QORE_EXECUTABLE="${QORE_QCC_QORE_EXECUTABLE:-}" \
                QORE_QCC_SOURCE_ORDER_HELPER="$source_order_tool" \
                QORE_QCC_BATCH_BOOTSTRAP_HELPER="$batch_bootstrap_tool" \
                QORE_QCC_LOCK_HELPER="${QORE_QCC_LOCK_HELPER:-}" \
                QORE_QCC_GRAPH_SNAPSHOT="$graph_snapshot" \
                "$incremental_tool" "$output" "$source" "$single_script"; then
            :
        else
            component_rc=$?
            # 78: qcc could not load or resolve the objects preloaded for this compile.
            # That is a property of the preload set this scheduler chose, not of the
            # source, and the group's own parse preloads nothing -- so it is answered
            # the way a failed partial parse is, with that parse, instead of leaving an
            # edit unbuildable because of which components it happened to make stale.
            # Any other failure is the source's own and fails the build now, without
            # paying for a group parse first.
            if [ "$component_rc" -eq 78 ]; then
                echo "$0: the objects preloaded to compile stale component" \
                    "$component_key could not be resolved; falling back to the" \
                    "group's own parse, which preloads nothing" >&2
                rm -f "$stale_file.components"
                escalate_to_group_batch
            fi
            # A compile that read a stale peer's previous object cannot be told
            # apart from a broken source; see preloads_pending_component().  A
            # real error fails the group's parse as well, and is reported there.
            if preloads_pending_component "$component_key" "$row"; then
                echo "$0: stale component $component_key was compiled against" \
                    "the previous object of a stale component it preloads, which" \
                    "a cycle of content dependencies left for later in this pass;" \
                    "falling back to the group's own parse, which preloads nothing" >&2
                rm -f "$stale_file.components"
                escalate_to_group_batch
            fi
            echo "$0: cannot build stale component $component_key" >&2
            exit 1
        fi
    done < "$stale_file.components"
    rm -f "$stale_file.components"
    compiled_total=$((compiled_total + stale_count))
    phase=$((phase + 1))
done
